Home > Blockchain >  Get distinct array of objects in javascript
Get distinct array of objects in javascript

Time:01-25

Distinct array of objects as like below; i want to get unique array of objects.

Example Array:

const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C  " }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]

Expected Output:

const data = [ { "name": "abc", age: "31", project: "Java" },{ "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C  " }]

CodePudding user response:

let unique = [...new Set(data.map(i => JSON.stringify(i)))].map(i => JSON.parse(i));

CodePudding user response:

This approach enforces a consistent key order, and uses JSON.stringify on each object to test for uniqueness.

const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C  " }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }]

const result = [...new Set(data.map(i=>JSON.stringify(Object.fromEntries(
  Object.entries(i).sort(([a],[b])=>a.localeCompare(b))))
))].map(JSON.parse)

console.log(result)

CodePudding user response:

As per your data, project property is containing dynamic values. Hence, You can filtered out the duplicates with in a single line of code by using Array.filter() method.

Live Demo :

const data = [ { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "29", project: "Javascript" }, { "name": "abc", age: "31", project: "C  " }, { "name": "abc", age: "31", project: "Java" }, { "name": "abc", age: "31", project: "Java" }];

const uniq = {};

var arrFiltered = data.filter(obj => !uniq[obj.project] && (uniq[obj.project] = true));

console.log(arrFiltered);

  • Related