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

การกรองค่าอาร์เรย์ที่ไม่ซ้ำและบวกผลรวมใน JavaScript


ภาพรวม

สมมติว่าเรามีอาร์เรย์ของอาร์เรย์:

const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];

ทุกซับอาร์เรย์มี 3 อิลิเมนต์ ฟังก์ชันควรกรองซับอาร์เรย์ที่มีค่าแรกซ้ำ และบวกค่าที่สามของซับอาร์เรย์ที่ถูกลบ เข้าไปในซับอาร์เรย์ที่ไม่ซ้ำ

ผลลัพธ์ที่คาดหวัง

const output = [[12345, "product", "25"],[1234567, "other", "10"]];

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

const arr = [[12345, "product", "10"],[12345, "product", "15"],[1234567, "other", "10"]];

const addSimilar = (arr = []) => {
  const res = [];
  const map = {};
  arr.forEach(el => {
    const [id, name, amount] = el;
    if(map.hasOwnProperty(id)) {
      const newAmount = +amount + +res[map[id] - 1][2];
      res[map[id] - 1][2] = '' + newAmount;
    } else {
      map[id] = res.push(el);
    }
  });
  return res;
};

console.log(addSimilar(arr));

ผลลัพธ์ในคอนโซล

[ [ 12345, 'product', '25' ], [ 1234567, 'other', '10' ] ]