- The
filter()
method creates a new array with array elements that passes a test. - The
filter()
method takes a callback function which has 3 arguments:- The item value
- The item index
- The array itself
In this example I am you looking to simply remove all objects(items in the array) for which a category has already appeared once. You can do this with the Vanilla Javascript filter method. You simply have to use an object to keep count of whether the object has appeared before or not.
var places = [{
"category": "other",
"title": "harry University",
"value": 4788,
"id": "1"
},
{
"category": "traveling",
"title": "tommy University",
"value": 5460,
"id": "2"
},
{
"category": "education",
"title": "jerry University",
"value": 7853456,
"id": "3"
},
{
"category": "business",
"title": "Charlie University",
"value": 6779589,
"id": "4"
},
{
"category": "business",
"title": "NYU",
"value": 0117824,
"id": "5"
}
];
function removeDuplicates(arrToBeFiltered, keyToMatch){
let dups = {};
return arrToBeFiltered.filter(function(item){
if(item[keyToMatch] in dups){return false;}
else {
dups[item[keyToMatch]] = true; return true;
}});
}
console.log(removeDuplicates(places,'category'));