สมมติเรามีอาร์เรย์ของออบเจ็กต์แบบนี้:
const arr = [ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ];เราต้องเขียนฟังก์ชันที่แยกออบเจ็กต์เป็นอาร์เรย์ย่อยแยกกันที่มีค่า uuid เหมือนกัน
ผลลัพธ์
ผลลัพธ์ควรเป็น:
const output = [ [ {"name": "toto", "uuid": 1111}, {"name": "titi", "uuid": 1111} ], [ {"name": "tata", "uuid": 2222} ] ];โค้ดสำหรับนี้:
const arr = [ {"name": "toto", "uuid": 1111}, {"name": "tata", "uuid": 2222}, {"name": "titi", "uuid": 1111} ]; const groupByElement = arr => { const hash = Object.create(null), result = []; arr.forEach(el => { if (!hash[el.uuid]) { hash[el.uuid] = []; result.push(hash[el.uuid]); }; hash[el.uuid].push(el); }); return result; }; console.log(groupByElement(arr));ผลลัพธ์
ผลลัพธ์ในคอนโซล:
[ [ { name: 'toto', uuid: 1111 }, { name: 'titi', uuid: 1111 } ], [ { name: 'tata', uuid: 2222 } ] ]