Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Remove duplicates and map an array in JavaScript
When working with arrays of objects, a common task is extracting unique values from a specific property. This tutorial shows how to remove duplicates and map an array to extract unique "name" values from objects.
Problem Statement
Suppose we have an array of objects like this:
const arr = [
{id: 123, value: "value1", name: "Name1"},
{id: 124, value: "value2", name: "Name1"},
{id: 125, value: "value3", name: "Name2"},
{id: 126, value: "value4", name: "Name2"}
];
Note that some "name" properties are duplicated. We need to create a new array containing only unique "name" values.
The expected output should be:
["Name1", "Name2"]
Using Traditional Loop Method
This approach uses a for loop with indexOf() to check for duplicates:
const arr = [
{id: 123, value: "value1", name: "Name1"},
{id: 124, value: "value2", name: "Name1"},
{id: 125, value: "value3", name: "Name2"},
{id: 126, value: "value4", name: "Name2"}
];
const pickNames = (arr = []) => {
const res = [];
for (let i = arr.length; i--;) {
if (res.indexOf(arr[i].name)
[ 'Name2', 'Name1' ]
Using Set and Map (Modern Approach)
A more efficient and readable solution using ES6 Set:
const arr = [
{id: 123, value: "value1", name: "Name1"},
{id: 124, value: "value2", name: "Name1"},
{id: 125, value: "value3", name: "Name2"},
{id: 126, value: "value4", name: "Name2"}
];
const getUniqueNames = (arr) => {
return [...new Set(arr.map(obj => obj.name))];
};
console.log(getUniqueNames(arr));
[ 'Name1', 'Name2' ]
Using Filter with findIndex
Another approach that preserves the first occurrence of each unique name:
const arr = [
{id: 123, value: "value1", name: "Name1"},
{id: 124, value: "value2", name: "Name1"},
{id: 125, value: "value3", name: "Name2"},
{id: 126, value: "value4", name: "Name2"}
];
const filterUniqueNames = (arr) => {
return arr
.filter((obj, index) => arr.findIndex(item => item.name === obj.name) === index)
.map(obj => obj.name);
};
console.log(filterUniqueNames(arr));
[ 'Name1', 'Name2' ]
Comparison
| Method | Performance | Readability | Order Preserved |
|---|---|---|---|
| Traditional Loop | Good | Medium | Reverse order |
| Set + Map | Best | High | Yes |
| Filter + findIndex | Slower for large arrays | High | Yes |
Conclusion
The Set with map() approach is the most efficient and readable method for removing duplicates from object arrays. Use filter() with findIndex() when you need more control over the filtering logic.
