根據另一個單詞陣列對單詞陣列進行排序 JavaScript


假設我們有如下根據 id 屬性排序的物件陣列 −

const unordered = [{
   id: 1,
   string: 'sometimes'
}, {
   id: 2,
   string: 'be'
}, {
   id: 3,
   string: 'can'
}, {
   id: 4,
   string: 'life'
}, {
   id: 5,
   string: 'tough'
}, {
   id: 6,
   string: 'very'
}, ];

還有如下一個字串陣列 −

const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough'];

我們需要對第一個陣列進行排序,使其字串屬性與第二個陣列中的字串次序相同。下面來編寫此程式碼。

示例

const unordered = [{
   id: 1,
   string: 'sometimes'
}, {
   id: 2,
   string: 'be'
}, {
   id: 3,
   string: 'can'
}, {
   id: 4,
   string: 'life'
}, {
   id: 5,
   string: 'tough'
}, {
   id: 6,
   string: 'very'
}, ];
const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough'];
const sorter = (a, b) => {
   return ordered.indexOf(a.string) - ordered.indexOf(b.string);
};
unordered.sort(sorter);
console.log(unordered);

輸出

控制檯的輸出將為 −

[
   { id: 4, string: 'life' },
   { id: 1, string: 'sometimes' },
   { id: 3, string: 'can' },
   { id: 2, string: 'be' },
   { id: 6, string: 'very' },
   { id: 5, string: 'tough' }
]

更新於: 21-Aug-2020

287 次檢視

開始您的 職業

透過完成課程獲得認證

入門
廣告