Remove Duplicate Objects inside Javascript Array

Known:

I have this array of objects:

[{id_product: "48", id_component: "1193", quantity: "1.00000", tq: "100"},
{id_product: "47", id_component: "1193", quantity: "1.00000", tq: "100"},
{id_product: "54", id_component: "1189", quantity: "1.00000", tq: "50"},
{id_product: "51", id_component: "809", quantity: "1.00000", tq: "120"},
{id_product: "55", id_component: "1189", quantity: "1.00000", tq: "50"},
{id_product: "49", id_component: "809", quantity: "1.00000", tq: "120"}]

Wanted:

I want to remove object that has duplicate id_component like “1193” and “809”

Wanted Result:

[{id_product: "48", id_component: "1193", quantity: "1.00000", tq: "100"},
{id_product: "54", id_component: "1189", quantity: "1.00000", tq: "50"},
{id_product: "51", id_component: "809", quantity: "1.00000", tq: "120"}]

Question:

How to do it … ?

Answer:

We can filter the array and find the index where the object has the same id_component with this code below:

let arrProduk= [{id_product: "48", id_component: "1193", quantity: "1.00000", tq: "100"},
{id_product: "47", id_component: "1193", quantity: "1.00000", tq: "100"},
{id_product: "54", id_component: "1189", quantity: "1.00000", tq: "50"},
{id_product: "51", id_component: "809", quantity: "1.00000", tq: "120"},
{id_product: "55", id_component: "1189", quantity: "1.00000", tq: "50"},
{id_product: "49", id_component: "809", quantity: "1.00000", tq: "120"}];

arrProduk = arrProduk.filter((objek, index, self) =>
    index === self.findIndex((t) => (
         t.id_component === objek.id_component
  ) )
 )

Thanks for reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *