group array of objects by id

后端 未结 8 536
抹茶落季
抹茶落季 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:21

    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'},
    ];
    
    let result = [];
    for (let i = 0; i < numberOfGroupsIWantToMake; i++) {
        let newGroupArray = api_array.filter(obj => obj.id === i);
        result.push(newGroupArray);
    }
    
    return result;
    

    Note: this is A solution, but it's not as performant as we're going over the entire array n number of times.

提交回复
热议问题