To find duplicate values in an array of objects in JavaScript, you can use the reduce
method along with an object to keep track of the values you have seen so far. If a value is already in the object, it is a duplicate.
Here’s an example:
function findDuplicates(arr) {
let duplicates = [];
let seen = {};
arr.forEach(function(obj) {
if (!seen[obj.value]) {
seen[obj.value] = true;
} else {
duplicates.push(obj.value);
}
});
return duplicates;
}
let arr = [{value: 1}, {value: 2}, {value: 3}, {value: 2}];
let duplicates = findDuplicates(arr);
console.log("Duplicates: " + duplicates);
In this example, the code defines a function findDuplicates
that takes an array arr
as an argument. The function uses an object seen
to keep track of the values seen so far. If a value is already in the object, it is a duplicate and is pushed into the duplicates
array. The function then returns the duplicates
array. The code then calls the findDuplicates
function with the arr
value and logs the result to the console.
+ There are no comments
Add yours