在 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP