Remove duplicate objects from an array.

Software Engineer @YaraInternational | Full-stack developer | Problem solver |...
It’s a common use case in projects to remove duplicates from an array of objects in JavaScript and It’s helpful for coding challenges to practice.
We are given an array of objects and the task is to remove the duplicate object element from the array list.
In this article. We will see multiple ways to remove duplicates from an array of objects.
The following way -
Higher-order functions(map, filter, reduce)
iterative way
using Set object
using Map object
const array = [
{"id": 5, "name": "Johnson"}, {"id": 4, "name": "John"},
{"id": 3, "name": "Juliet"}, {"id": 2, "name": "Nancy"},
{"id": 5, "name": "Johnson"}, {"id": 5, "name":"Johnson"},
{"id": 2, "name": "Nancy"}, {"id": 3, "name": "Juliet"}
];
Higher-order functions
const uniqueData = [...new Map(array.map(item => [item.id, item])).values()];
console.table(uniqueData);
const uniq = {};
const uniqueData = array.filter(obj => {
return !uniq[obj.id] && (uniq[obj.id] = true)
});
console.table(uniqueData);
let uniqueData = array.reduce((arr, item) => {
const filtered = arr.filter(i => i['id'] !== item['id']);
return [...filtered, item];
}, []);
console.table(uniqueData);
To get output in tabular data as a table you can use console.table()

Iterative
function unique(array) {
const uniqueArr = [];
const uniqueObject = {};
for (let i in array) {
objTitle = array[i].name;
uniqueObject[objTitle] = array[i];
}
for (let i in uniqueObject) {
uniqueArr.push(uniqueObject[i]);
}
console.table(uniqueArr);
}
unique(array);
Another way
const result = {};
for (let i = 0, n = array.length; i < n; i++) {
result[array[i].name] = array[i];
}
let unique = [], index = 0;
for(let item in result) {
unique[index++] = result[item];
}
console.table(unique);
Using Set
The Setobject lets you store unique values of any type, whether primitive values or object references.
function unique(arr) {
const jsonObject = arr.map(JSON.stringify);
uniqueSet = new Set(jsonObject);
uniqueArray = Array.from(uniqueSet).map(JSON.parse);
console.table(uniqueArray);
}
unique(array);
Using Map
The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
const uniqueData = [];
const map = new Map();
for (const object of array) {
if (!map.has(object.id)) {
map.set(object.id, true);
uniqueData.push({
id: object.id,
name: object.name
});
}
}
console.table(uniqueData);


That’s all! I hope this article might be helpful to remove duplicates from an array of objects.
Thanks for reading ❤.
Say Hello! Twitter | Blog | LinkedIn | Github


