Remove duplicate objects from an array.
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.
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
let 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
- map
let output = [...new Map(array.map(item => [item.id, item])).values()]; console.table(output);
- filter
let uniq = {};
let output = array.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));console.table(output);
- reduce
let output = array.reduce((arr, item) => {
const filtered= arr.filter(i => i['id'] !== item['id']);
return [...filtered, item];
}, []);console.table(output);
To get output in tabular data as a table you can use console.table()
Output
-Iterative
function unique(arr) {
let uniqueArr = [];
let uniqueObject = {};
for (let i in arr) {
objTitle = arr[i].name;
uniqueObject[objTitle] = arr[i];
}
for (let i in uniqueObject) {
uniqueArr.push(uniqueObject[i]);
}
console.table(uniqueArr);
}
unique(array);
let result = {};
for (let i = 0, n = array.length; i < n; i++) {
let item = array[i];
result[item.name] = item;
}let unique = [];
let index = 0;
for(let item in result) {
unique[index++] = result[item];
}
console.log(unique);
-Set
The Set
object lets you store unique values of any type, whether primitive values or object references.
function unique(arr) {
jsonObject = arr.map(JSON.stringify);
uniqueSet = new Set(jsonObject);
uniqueArray = Array.from(uniqueSet).map(JSON.parse);
console.table(uniqueArray);
} unique(array);
let output = Array.from(new Set(array.map(a => a.id))).map(id => {
return array.find(a => a.id === id)
})console.table(output);
-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 output = [];
const map = new Map();
for (const object of array) {
if (!map.has(object.id)) {
map.set(object.id, true);
output.push({
id: object.id,
name: object.name
});
}
}console.table(output);
That’s all! I hope this article might be helpful to remove duplicates from an array of objects.
Thanks for reading…