Giả sử chúng ta có mảng object sau đã sắp xếp theo 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' },
];Và một mảng chuỗi khác:
const ordered = ['Life', 'sometimes', 'can', 'be', 'very', 'tough'];Cần sắp xếp mảng đầu tiên sao cho thuộc tính string có cùng thứ tự với mảng thứ hai.
Ví dụ
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);Kết quả
Đầu ra trong console sẽ là:
[
{ id: 4, string: 'life' },
{ id: 1, string: 'sometimes' },
{ id: 3, string: 'can' },
{ id: 2, string: 'be' },
{ id: 6, string: 'very' },
{ id: 5, string: 'tough' }
]