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
I'm a little late to the party but this might help someone who's facing the same problem, as it is, I believe, an easier to understand solution:
let duplicates = [];
array.forEach((el, i) => {
array.forEach((element, index) => {
if (i === index) return null;
if (element.name === el.name && element.Age === el.Age) {
if (!duplicates.includes(el)) duplicates.push(el);
}
});
});
console.log("duplicates", duplicates);
Two things might be tricky to understand:
Edit: An even nicer solution would be this:
const duplicates = array
.map((el, i) => {
return array.find((element, index) => {
if (i !== index && element.name === el.name && element.Age === el.Age) {
return el
}
})
})
.filter(x => x)
console.log("dupliactes:", duplicates)
It has no side effects and all logic is in one if statement. The filter is needed to sort out undefined instances.