สมมติเรามีอาร์เรย์สองมิติของตัวเลขแบบนี้:
const arr = [ [1, 3, 2], [5, 2, 1, 4], [2, 1] ];
เราต้องเขียนฟังก์ชันที่จัดกลุ่มตัวเลขที่เหมือนกันทั้งหมดใน subarray ของตัวเอง แล้วเรียงกลุ่มให้อยู่ในลำดับเพิ่ม
ผลลัพธ์สุดท้ายควรเป็น:
const output = [ [1, 1, 1], [2, 2, 2], [4], [3], [5] ];
ตัวอย่าง
โค้ดสำหรับนี้:
const arr = [ [1, 3, 2], [5, 2, 1, 4], [2, 1] ]; const groupAndSort = arr => { const res = []; const map = Object.create(null); Array.prototype.forEach.call(arr, item => { item.forEach(el => { if (!(el in map)) { map[el] = []; res.push(map[el]); }; map[el].push(el); }); }); res.sort((a, b) => { return a[0] - b[0]; }); return res; }; console.log(groupAndSort(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
[ [ 1, 1, 1 ], [ 2, 2, 2 ], [ 3 ], [ 4 ], [ 5 ] ]