在 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 ]

更新於:25-Aug-2020

3K+ 瀏覽量

啟動你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.