Imagine you have an array filled with different objects:
var itemsArray = [
{name: "apple", color: "red", weight: "100g"},
{name: "banana", color: "yellow", weight: "120g"},
{name: "apple", color: "red", weight: "100g"},
{name: "banana", color: "yellow", weight: "120g"},
{name: "orange", color: "orange", weight: "150g"},
{name: "grape", color: "purple", weight: "80g"},
{name: "orange", color: "orange", weight: "150g"}
];
We want to filter this array to remove duplicate objects:
var itemsArray = [
{name: "apple", color: "red", weight: "100g"},
{name: "banana", color: "yellow", weight: "120g"},
{name: "orange", color: "orange", weight: "150g"},
{name: "grape", color: "purple", weight: "80g"}
];
While filtering arrays of plain strings is simple:
itemsArray.filter(function (value, index, self) {
return self.indexOf(value) === index;
}
It doesn't work for objects. We need to compare all properties to achieve this. Perhaps a deep comparison method is required?