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