假设,我们根据其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' } ]