Ad

To Remove Duplicate Among Array Of Objects Corresponding To The Other Key And Value Pair Of Object Using Javascript

Have an array of objects with object having two key and value pairs.

[{fruit:"apple",locale:"US"},
{fruit:"orange",locale:"US"},
{fruit:"banana",locale:"US"},
{fruit:"apple",locale:"US"},
{fruit:"orange",locale:"IT"},
{fruit:"apple",locale:"IT"},
{fruit:"banana",locale:"IT"},
{fruit:"orange",locale:"IT"}
{fruit:"apple",locale:"IT"}]

How to achieve Fruit should not be duplicate within same locale, Fruit can be same with different locales.

Ad

Answer

You can filter out the objects by matching the index value of current iteration. Something like this:

var data=[{fruit:"apple",locale:"US"},{fruit:"orange",locale:"US"},{fruit:"banana",locale:"US"},{fruit:"apple",locale:"US"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"},{fruit:"banana",locale:"IT"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"}];

var result = data.filter((e,i,self)=>self.findIndex(k=>k.fruit==e.fruit && k.locale==e.locale)==i);

console.log(result);

Or you can make use of Map:

var data=[{fruit:"apple",locale:"US"},{fruit:"orange",locale:"US"},{fruit:"banana",locale:"US"},{fruit:"apple",locale:"US"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"},{fruit:"banana",locale:"IT"},{fruit:"orange",locale:"IT"},{fruit:"apple",locale:"IT"}];

var result = [...new Map(data.map(k=>[`${k.fruit}|${k.locale}`, k])).values()];

console.log(result);
 

Ad
source: stackoverflow.com
Ad