Remove/ filter duplicate records from array - JavaScript?


Let’s say the following are our records with some duplicate values −

var objectOfNationality =
   [
      { nationality: "Indian" },
      { nationality: "American" },
      { nationality: "Emirati" },
      { nationality: "Indian" },
      { nationality: "American" }
   ];

Example

To remove duplicate records, use the concept of Set().Following is the code −

var objectOfNationality =
   [
      { nationality: "Indian" },
      { nationality: "American" },
      { nationality: "Emirati" },
      { nationality: "Indian" },
      { nationality: "American" }
   ];
function removeOrFilterNationality(objectOfNationality) {
   return Array.from(new Set(objectOfNationality.map(tempObject => tempObject.nationality)));
}
console.log(removeOrFilterNationality(objectOfNationality));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo228.js.

Output

The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo228.js
[ 'Indian', 'American', 'Emirati' ]

Updated on: 03-Oct-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements