除某些 JavaScript 單詞外,按照字母順序對訂單項進行排序


假設我們有兩個陣列都包含字串常量,其中一個需要按字母順序排序,但如果此陣列(我們要排序的陣列)包含來自另一個數組的某些單詞,那麼這些單詞應顯示在頂部,並且元素的其餘部分應按字母順序排序。

讓我們編寫一個名為 excludeSorting(arr, ex) 的函式,其中 arr 是要排序的陣列,ex 是應出現在 arr 頂部的字串陣列(如果它們出現在 arr 中)。

示例

const arr = ['apple', 'cat', 'zebra', 'umbrella', 'disco', 'ball',
'lemon', 'kite', 'jack', 'nathan'];
const toBeExcluded = ['disco', 'zebra', 'umbrella', 'nathan'];
const excludeSort = (arr, ex) => {
   arr.sort((a, b) => {
      if(ex.includes(a)){
         return -1;
      }else if(ex.includes(b)){
         return 1;
      }
      return a > b ? 1 : -1
   });
};
excludeSort(arr, toBeExcluded);
console.log(arr);

輸出

控制檯中的輸出將為 -

[
   'nathan', 'disco',
   'umbrella', 'zebra',
   'apple', 'ball',
   'cat', 'jack',
   'kite', 'lemon'
]

更新於: 21-8-2020

76 次瀏覽

開啟你的 職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.