ecmascript 6 - Javascript ES6 Map an array of objects into Set or filter out by distinct property - Stack Overflow

I have an object array with property of name and age, I would like to filter out a collection of distin

I have an object array with property of name and age, I would like to filter out a collection of distinct age among the array, so I can do something like

function distinctAges() {
    const guests = [
          {name: 'Kiley', age: 24}, 
          {name: 'Tom', age: 36}, 
          {name: 'Jason', age: 67},
          {name: 'Mike', age: 24},
          ...];

    let ageSet = new Set();
    guests.foreach(g => ageSet.add(g.age));
    return ageSet;
}

Is there anyway not using the Set datatype, like a Distinct operation? Of if using the Set, is there anyway to write the conversion in one line?

I have an object array with property of name and age, I would like to filter out a collection of distinct age among the array, so I can do something like

function distinctAges() {
    const guests = [
          {name: 'Kiley', age: 24}, 
          {name: 'Tom', age: 36}, 
          {name: 'Jason', age: 67},
          {name: 'Mike', age: 24},
          ...];

    let ageSet = new Set();
    guests.foreach(g => ageSet.add(g.age));
    return ageSet;
}

Is there anyway not using the Set datatype, like a Distinct operation? Of if using the Set, is there anyway to write the conversion in one line?

Share Improve this question asked Apr 30, 2020 at 22:21 DrexDrex 3,87110 gold badges46 silver badges77 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Sets are the JS current way of getting an array of distinct values. You can map an array of objects to an array of values, create a Set, and then spread back to an array:

const distinctBy = (prop, arr) => [...new Set(arr.map(o => o[prop]))]

const guests = [{"name":"Kiley","age":24},{"name":"Tom","age":36},{"name":"Jason","age":67},{"name":"Mike","age":24}]

const result = distinctBy('age', guests)

console.log(result)

To make this more generic, you can replace the prop with a predicate function:

const distinctBy = (predicate, arr) => [...new Set(arr.map(predicate))]

const guests = [{"name":"Kiley","age":24},{"name":"Tom","age":36},{"name":"Jason","age":67},{"name":"Mike","age":24}]

const result = distinctBy(o => o.age, guests)

console.log(result)

Actually you also may just use .reduce

      const guests = [
          {name: 'Kiley', age: 24}, 
          {name: 'Tom', age: 36}, 
          {name: 'Jason', age: 67},
          {name: 'Mike', age: 24}]
      
    console.log(guests.reduce((acc, rec) => acc.includes(rec.age) ? acc : [...acc, rec.age], []))

or with Set in one line:

      const guests = [
          {name: 'Kiley', age: 24}, 
          {name: 'Tom', age: 36}, 
          {name: 'Jason', age: 67},
          {name: 'Mike', age: 24}]
          
console.log([...new Set(guests.map(it => it.age))])

There are lots of ways to do this -- the question is "how to determine uniqueness", which is often problem-domain dependent.

One trick I frequently use if I can't use Set is to collide property names in a junk object, because this tends to be quite fast for reasonable sized-sets in JavaScript --

let seen={};
let ageList=guests.filter((obj) => { 
  let ret = !seen[obj.age];
  seen[obj.age] = true; 
  return ret;
}).map((obj) => obj.age);
console.log(ageList);

This code sets a property in seen which has the same name as your age during the filter function. If it was unset, it returns true, so that that record will be part of the filtered array. Then I apply a map function which maps guest objects to ages. The result is an array which contains all of the unique ages.

One optimization might be to use a spare Array instead of an Object to determine uniqueness, knowing (assuming) that all ages are numbers and they tend to be quite small -- simply change seen={} to seen=[] in the example above.

Of course, Knuth would point out that premature optimization is the root of all evil -- and I would point out that if you care about optimization you also need to measure....

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745453521a4628379.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信