JavaScript native groupBy reduce

后端 未结 5 558
甜味超标
甜味超标 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:25

    You could use a Map and a stringified object as key for grouping.

    Later render the wanted array with objects of the keys and the grouped persons.

    var 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" }],
        arranged = Array.from(
            people.reduce((m, o) => {
                var key = JSON.stringify(Object.assign(...['city', 'state'].map(k => ({ [k]: o[k] }))));
                return m.set(key, (m.get(key) || []).concat({ name: o.name, age: o.age }));
            }, new Map),
            ([key, persons]) => Object.assign(JSON.parse(key), { persons })
        );
    
    console.log(arranged);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题