สมมติว่าเรามีอาร์เรย์ของอ็อบเจ็กต์ที่จัดเรียงตามคุณสมบัติของ 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' }
]