在 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