group array of objects by id

后端 未结 8 532
抹茶落季
抹茶落季 2021-01-16 08:07

I am trying to loop through a array ob objects and group the items of the array into new arrays that have matching id:

API example:

    api_array [
          


        
相关标签:
8条回答
  • 2021-01-16 08:33

    You could take a Map for grouping same id and get the values from the map as result set.

    The result set has the same order of the wanted keys.

    function groupBy(array, key) {
        return Array.from(array
            .reduce((m, o) => m.set(o[key], [...(m.get(o[key]) || []), o]), new Map)
            .values()
        );
    }
    
    var data = [{ id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx' }, { id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx' }],
        grouped = groupBy(data, 'id');
    
    console.log(grouped);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2021-01-16 08:34

    Similar to your reduce example, this iterates over the data and creates a object using the object ids as keys and grouping them together. It then grabs the values from that object.

    const api_array = [{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 1, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 2, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 3, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'},{id: 4, postcode: 'xxx', street: 'xxx', city: 'xxx'}];
    
    const out = Object.values(api_array.reduce((acc, c) => {
      const { id } = c;
    
      // If the object doesn't have a key that matches the id
      // create an array as its value and then concat the current object
      // to it, otherwise, if the key exists just concat the current object
      // to the existing array
      acc[id] = (acc[id] || []).concat(c);
      return acc;
    }, {}));
    
    console.log(out)

    0 讨论(0)
提交回复
热议问题