查找并返回多个值的数组位置JavaScript
我们必须编写一个函数,例如findPositions(),它接受两个数组作为参数。并且它应该返回第一个数组中存在的第二个数组的所有元素的索引的数组。
例如-
If the first array is [‘john’, ‘doe’, ‘chris’, ‘snow’, ‘john’, ‘chris’], And the second array is [‘john’, chris]
那么输出应该是-
[0, 2, 4, 5]
因此,让我们为该函数编写代码。我们将在这里使用forEach()循环;
示例
const values = ['michael', 'jordan', 'jackson', 'michael', 'usain',
'jackson', 'bolt', 'jackson'];
const queries = ['michael', 'jackson', 'bolt'];
const findPositions = (first, second) => {
const indicies = [];
first.forEach((element, index) => {
if(second.includes(element)){
indicies.push(index);
};
});
return indicies;
};
console.log(findPositions(values, queries));输出结果
控制台中的输出将为-
[ 0, 2, 3, 5, 6, 7 ]
热门推荐
10 虎年新年专属祝福语简短
11 简短霸气的考试祝福语
12 20岁简短生日祝福语
13 送去考试祝福语大全简短
14 生日祝福语贺卡文字简短
15 姐姐女儿结婚祝福语简短
16 小红书平安祝福语简短
17 大寿爸爸祝福语简短英文
18 班级集体生日祝福语简短