根据另一个单词数组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'];
我们必须对第一个数组进行排序,以便其string属性具有与第二个数组相同的字符串顺序。因此,让我们为此编写代码。
示例
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' }
]热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便