Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

จัดกลุ่มอาร์เรย์ 2 มิติตามคอลัมน์แรก - JavaScript

จากอาร์เรย์ของ [key, value] จัดกลุ่ม Value ทั้งหมดที่มี Key เดียวกัน

ตัวอย่าง

[[1,45], [1,34], [1,49], [2,34], [4,78], [2,67], [4,65]]
→ [[45,34,49], [34,67], [78,65]]

ตัวอย่างโค้ด

const constructSimilarArray = arr => 
  arr.reduce((acc, [key, val]) => {
    if (!acc.map.has(key)) {
      acc.map.set(key, acc.res.push([val]) - 1);
    } else {
      acc.res[acc.map.get(key)].push(val);
    }
    return acc;
  }, { map: new Map(), res: [] }).res;

console.log(constructSimilarArray([[1,45],[1,34],[1,49],[2,34],[4,78],[2,67],[4,65]]));

ผลลัพธ์

[ [ 45, 34, 49 ], [ 34, 67 ], [ 78, 65 ] ]

วิธีแบบ Object (Simple)

const groupByFirst = arr => {
  const groups = {};
  for (const [key, val] of arr) {
    if (!groups[key]) groups[key] = [];
    groups[key].push(val);
  }
  return Object.values(groups);
};

ใช้ Object/Map จัดกลุ่มตาม Key แล้วดึง Values ออกมา