JavaScript native groupBy reduce

后端 未结 5 513
甜味超标
甜味超标 2021-01-23 08:30

I am using JavaScript native reduce, however I want to slightly change in the grouping to get my desired result. I have an array as follows:

const people = [
          


        
5条回答
  •  借酒劲吻你
    2021-01-23 09:12

    You can use the function reduce to group and build the desired output.

    const people = [  {name: "John", age: 23, city: "Seattle", state: "WA"},  {name: "Mark", age: 25, city: "Houston", state: "TX"},  {name: "Luke", age: 26, city: "Seattle", state: "WA"},  {name: "Paul", age: 28, city: "Portland", state: "OR"},  {name: "Matt", age: 21, city: "Oakland", state: "CA"},  {name: "Sam", age: 24, city: "Oakland", state: "CA"}]
    
    const result = Object.values(people.reduce((a, {name, age, city, state}) => {
      var key = [city, state].join('|');
      (a[key] || (a[key] = {city, state, persons: []})).persons.push({name, age});
      return a;
    }, {}));
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题