根据另一个单词数组对单词数组进行排序 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 次查看

开始您的 职业

通过完成课程获得认证

入门
广告
© . All rights reserved.