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
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.
Array. from() is an ECMAScript6 (ES6) feature.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With