Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading