如何在 JavaScript 中將多個元素移動到陣列的開頭?


我們必須編寫一個函式,該函式採用陣列和任意數量的字串作為引數。任務是檢查字串是否出現在陣列中。如果出現,我們必須將該特定元素移動到陣列的前面。

因此,讓我們為這個函式編寫程式碼 −

示例

const arr = ['The', 'weather', 'today', 'is', 'a', 'bit', 'windy.'];
const pushFront = (arr, ...strings) => {
   strings.forEach(el => {
      const index = arr.indexOf(el);
      if(index !== -1){
         arr.unshift(arr.splice(index, 1)[0]);
      };
   });
};
pushFront(arr, 'today', 'air', 'bit', 'windy.', 'rain');
console.log(arr);

輸出

控制檯中的輸出將是 −

[ 'windy.', 'bit', 'today', 'The', 'weather', 'is', 'a' ]

更新於: 2020-08-24

674 檢視

啟動你的 事業

完成課程獲取認證

入門
廣告
© . All rights reserved.