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
How to remove duplicate property values in array – JavaScript?
In JavaScript, you may need to remove duplicate values from array properties within an array of objects. This is common when working with data that contains repeated values that should be unique.
Problem Example
Consider an array of student objects where some students have duplicate marks in their studentMarks array:
var details = [
{
studentName: "John",
studentMarks: [78, 98]
},
{
studentName: "David",
studentMarks: [87, 87] // duplicate 87
},
{
studentName: "Bob",
studentMarks: [48, 58]
},
{
studentName: "Sam",
studentMarks: [98, 98] // duplicate 98
}
];
console.log("Original data:", details);
Original data: [
{ studentName: 'John', studentMarks: [ 78, 98 ] },
{ studentName: 'David', studentMarks: [ 87, 87 ] },
{ studentName: 'Bob', studentMarks: [ 48, 58 ] },
{ studentName: 'Sam', studentMarks: [ 98, 98 ] }
]
Using map() with Set to Remove Duplicates
We can use map() to iterate through each object and the Set constructor to remove duplicates from the studentMarks array:
var details = [
{
studentName: "John",
studentMarks: [78, 98]
},
{
studentName: "David",
studentMarks: [87, 87]
},
{
studentName: "Bob",
studentMarks: [48, 58]
},
{
studentName: "Sam",
studentMarks: [98, 98]
}
];
details.map(tempObj => {
if (typeof (tempObj.studentMarks) == 'object') {
tempObj.studentMarks = [...new Set(tempObj.studentMarks)];
if (tempObj.studentMarks.length == 1) {
tempObj.studentMarks = tempObj.studentMarks[0];
}
}
});
console.log(details);
[
{ studentName: 'John', studentMarks: [ 78, 98 ] },
{ studentName: 'David', studentMarks: 87 },
{ studentName: 'Bob', studentMarks: [ 48, 58 ] },
{ studentName: 'Sam', studentMarks: 98 }
]
How It Works
The solution works in these steps:
-
new Set(tempObj.studentMarks)creates a Set from the array, automatically removing duplicates -
[...new Set(...)]spreads the Set back into an array - If only one unique value remains, it converts the single-item array to just the value
-
map()applies this transformation to each object in the array
Alternative Approach: Preserving Arrays
If you want to keep all properties as arrays regardless of length:
var details = [
{ studentName: "David", studentMarks: [87, 87] },
{ studentName: "Sam", studentMarks: [98, 98] }
];
details.map(student => {
student.studentMarks = [...new Set(student.studentMarks)];
});
console.log(details);
[
{ studentName: 'David', studentMarks: [ 87 ] },
{ studentName: 'Sam', studentMarks: [ 98 ] }
]
Conclusion
Using map() with Set is an efficient way to remove duplicate values from array properties. The Set constructor automatically handles duplicate removal, making the code clean and readable.
