ภาพรวม
สมมติว่าเรามีอาร์เรย์สองอาร์เรย์:
const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
เราต้องเขียนฟังก์ชันที่จัดเรียงอิลิเมนต์ของอาร์เรย์แรกตามตำแหน่งในอาร์เรย์ที่สอง
ตัวอย่างโค้ด
const input = ['S-1','S-2','S-3','S-4','S-5','S-6','S-7','S-8'];
const sortingArray = ["S-1", "S-5", "S-2", "S-6", "S-3", "S-7", "S-4", "S-8"];
const sortByReference = (arr1 = [], arr2 = []) => {
const sorter = (a, b) => {
const firstIndex = arr2.indexOf(a);
const secondIndex = arr2.indexOf(b);
return firstIndex - secondIndex;
};
arr1.sort(sorter);
};
sortByReference(input, sortingArray);
console.log(input);
ผลลัพธ์ในคอนโซล
[ 'S-1', 'S-5', 'S-2', 'S-6', 'S-3', 'S-7', 'S-4', 'S-8' ]