Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding distinct object in array by es6

I have an array like below

const data = [
    {
        name:'AAAA',
        group: 'A',
        age:10
    },
    {
        name:'ABCD',
        group: 'A',
        age:10
    },
    {
        name:'DJSHDJH',
        group: 'B',
        age:15
    },
    {
        name:'FJHF',
        group: 'B',
        age:20
    }
]

I want to find distinct data by group and age by es6

expected result

[
    {
        group: 'A',
        age: 10
    },
    {
        group: 'B',
        age: 15
    },
    {
        group: 'B',
        age: 20
    }
]

I tried using [... new Set(data.map(x => {x.group, g.age}))] but no chance

I know how to loop through data and find unique values, but I want to use es6 functions

like image 783
Reza Avatar asked Aug 03 '17 14:08

Reza


People also ask

How do you filter an array of objects?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Is array from ES6?

Array. from() is an ECMAScript6 (ES6) feature.


1 Answers

You can use Object.values() with reduce() to return array of values as result.

const data = [{"name":"AAAA","group":"A","age":10},{"name":"ABCD","group":"A","age":10},{"name":"DJSHDJH","group":"B","age":15},{"name":"FJHF","group":"B","age":20}]

var result = Object.values(data.reduce((r, e) => (r[e.group + '|' + e.age] = {group: e.group, age: e.age}, r), {}))
console.log(result)

Another way of writing the same code as suggested by @Jeremy Thille is using template literals and property value shorthand

const data = [{"name":"AAAA","group":"A","age":10},{"name":"ABCD","group":"A","age":10},{"name":"DJSHDJH","group":"B","age":15},{"name":"FJHF","group":"B","age":20}]

var result = Object.values(data.reduce(function(r, e) {
  let group = e.group, age = e.age;
  return r[`${group}|${age}`] = {group, age}, r
}, {}))

console.log(result)

You can also use ES6 parameter destructuring as suggested by @gyre.

const data = [{"name":"AAAA","group":"A","age":10},{"name":"ABCD","group":"A","age":10},{"name":"DJSHDJH","group":"B","age":15},{"name":"FJHF","group":"B","age":20}]

var result = Object.values(data.reduce((r, {group, age}) => (r[group+'|'+age] = {group, age}, r), {}))
console.log(result)
like image 134
Nenad Vracar Avatar answered Oct 23 '22 05:10

Nenad Vracar