Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove array duplicates by property - JavaScript
Suppose, we have an array of objects like this −
const arr = [{name: "Jack", age: "14"},{name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}, {name: "Jack", age: "21"}];
We are required to write a JavaScript function that takes in one such array and removes all the objects that have duplicate values for the name.
Therefore, for the above array, the output should be −
const arr = [{name: "Jack", age: "14"},{name: "bob", age: "14"}, {name: "sue", age: "21"}, {name: "Jill", age: "16"}];
Example
Following is the code −
const arr = [
{name: "Jack", age: "14"},
{name: "bob", age: "14"},
{name: "sue", age: "21"},
{name: "Jill", age: "16"},
{name: "Jack", age: "21"}
];
const removeDuplicate = arr => {
const appeared = {};
for(let i = 0; i < arr.length; ){
if(!appeared.hasOwnProperty(arr[i].name)){
appeared[arr[i].name] = 1;
i++;
continue;
};
arr.splice(i, 1);
};
};
removeDuplicate(arr);
console.log(arr);
Output
This will produce the following output in console −
[
{ name: 'Jack', age: '14' },
{ name: 'bob', age: '14' },
{ name: 'sue', age: '21' },
{ name: 'Jill', age: '16' }
]Advertisements