根据另一个单词数组对一个单词数组进行排序 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/1 19:24:17

假设我们有以下对象数组,根据其 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' }
]

相关文章


有用资源