查找并返回多个值的数组位置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 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短