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
Selected Reading
How to remove duplicate property values in array – JavaScript?
Let’s say the following is our array −
var details = [
{
studentName: "John",
studentMarks: [78, 98]
},
{
studentName: "David",
studentMarks: [87, 87]
},
{
studentName: "Bob",
studentMarks: [48, 58]
},
{
studentName: "Sam",
studentMarks: [98, 98]
},
]
We need to remove the duplicate property value i.e. 87 is repeating above. We need to remove it.
For this, use the concept of map().
Example
Following is the code −
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);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo292.js.
Output
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo292.js
[
{ studentName: 'John', studentMarks: [ 78, 98 ] },
{ studentName: 'David', studentMarks: 87 },
{ studentName: 'Bob', studentMarks: [ 48, 58 ] },
{ studentName: 'Sam', studentMarks: 98 }
] Advertisements
