Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter Array By Unique Value In Javascript

I have this 2 dimensional array

let values = [
  [ 6285646346643, 'TCN0018', 200, 2000, 5000, 4000 ],
  [ 6285646346644, 'TCN0018', 300, 2000, 5000, 3000 ],
  [ 6285646346645, 'TCN0019', 100, 1000, 5000, 4000 ]
];

I want to filter it by its second column, 'TCNXXX' and then sum its third column so its result should be as object like this:

{ TCN0018: 500, TCN0019: 100 }

Here is the code that I already implemented:

let values = [
  [ 6285646346643, 'TCN0018', 200, 2000, 5000, 4000 ],
  [ 6285646346644, 'TCN0018', 300, 2000, 5000, 3000 ],
  [ 6285646346645, 'TCN0019', 100, 1000, 5000, 4000 ]
];

let product_id = [];
let obj_product = {};
let amount = 0;
for(let i = 0; i < values.length; i++)
{
    if(product_id.indexOf(values[i][1]) === -1)
    {
        console.log(values[i][2])
        product_id.push(values[i][1]);
        amount = values[i][2];
    }    
    obj_product[values[i][1]] = amount;
}

console.log(obj_product);

//result
//{ TCN0018: 200, TCN0019: 100 }

Instead the result is:

{ TCN0018: 200, TCN0019: 100 }

I want to ask, how to achieve the desired result and what I could improve from my code so far?

like image 431
Vinotaz Avatar asked Dec 11 '25 16:12

Vinotaz


1 Answers

That's a groupBy logic, basically. Here's how you can implement it:

const values = [
  [ 6285646346643, 'TCN0018', 200, 2000, 5000, 4000 ],
  [ 6285646346644, 'TCN0018', 300, 2000, 5000, 3000 ],
  [ 6285646346645, 'TCN0019', 100, 1000, 5000, 4000 ]
];

const result = Object.create(null) // empty object, similar to {}

for (const value of values) {
  const id = value[1]; // 'TCNXXXX'
  const column = value[2];

  result[id] ??= 0; // initialise if that's the first encounter
  result[id] += column;
}

console.log(result)
like image 65
Dima Parzhitsky Avatar answered Dec 14 '25 05:12

Dima Parzhitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!