按 JavaScript 中陣列的索引來排序


假設我們有以下物件陣列 -

const arr = [
   {
      'name' : 'd',
      'index' : 3
   },
   {
      'name' : 'c',
      'index' : 2
   },
   {
      'name' : 'a',
      'index' : 0
   },
   {
      'name' : 'b',
      'index' : 1
   }
];

我們需要編寫一個 JavaScript 函式,該函式採用一個這樣的陣列。

該函式應按物件的 index 屬性對該陣列按升序排序。

然後,該函式應將排序後的陣列對映到一個字串陣列,其中每個字串都是物件 name 屬性值對應的值。

因此,對於上述陣列,最終輸出應如下所示 -

const output = ["a", "b", "c", "d"];

示例

相應的程式碼為 -

const arr = [
   {
      'name' : 'd',
      'index' : 3
   },
   {
      'name' : 'c',
      'index' : 2
   },
   {
      'name' : 'a',
      'index' : 0
   },
   {
      'name' : 'b',
      'index' : 1
   }
];
const sortAndMap = (arr = []) => {
   const copy = arr.slice();
   const sorter = (a, b) => {
      return a['index'] - b['index'];
   };
   copy.sort(sorter);
   const res = copy.map(({name, index}) => {
      return name;
   });
   return res;
};
console.log(sortAndMap(arr));

輸出

控制檯中的輸出為 -

[ 'a', 'b', 'c', 'd' ]

更新於: 2020-11-24

2K+ 次瀏覽

開啟你的職業生涯

透過完成課程以獲得認證

入門
廣告
© . All rights reserved.