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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With