I\'ve been trying to work out a problem I\'m having. I have an array with objects in it, like this:
var array = [
{
name: \"Steven Smith\",
Country
Here's an alternative solution, which I will point out the
let array = getData(); // sets up data array
let duplicates = array.filter(duplicatesOnly); // filter out duplicates
console.log( duplicates ); // output to console
/* ============================================================================= */
// Returns true/false based on a duplicate object being found
function duplicatesOnly(v1, i1, self) {
let ndx = self.findIndex(function(v2, i2) {
// make sure not looking at the same object (using index to verify)
// use JSON.stringify for object comparison
return (i1 != i2 && JSON.stringify(v1) == JSON.stringify(v2))
})
return i1 != ndx && ndx != -1
}
// Use function hoisting to place trivial code at the bottom of example
function getData() {
return [{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Hannah Reed",
Country: "Scottland",
Age: 23
},
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Robert Landley",
Country: "England",
Age: 84
},
{
name: "Steven Smith",
Country: "England",
Age: 35
},
{
name: "Robert Landley",
Country: "England",
Age: 84
}
];
}
JSON.stringify is being performed on two objects on each iteration (very expensive)JSON.stringify may create the string based on key order, so even if objects have the same keys/values, the order may be a factor when comparing the objects -- this could be seen as a benefit or a costfilter and findIndex the concentration was not on making it efficient. It could be improved by using caching and performing JSON.stringify once, or avoiding it altogether with something more customized.