-3

I want this array to be sorted by id value, so I want all userHandle that belongs to id 34 to be in ONE object and not separated.

Array [
      Object {
        "id": 34,
        "userHandle": "Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
      },
      Object {
        "id": 34,
        "userHandle": "LrIwIx9I1xQBJ7aeCSrinpEaDP53",
      },
      Object {
        "id": 33,
        "userHandle": " PNfyQdC2cWaxtGiMZhLT9g1Lc9H2",
      },
    ]
MatkoMilic
  • 55
  • 1
  • 11

2 Answers2

1

Something like this?

const arr = [
  {
    "id": 34,
    "userHandle": "Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
  },
  {
    "id": 34,
    "userHandle": "LrIwIx9I1xQBJ7aeCSrinpEaDP53",
  },
  {
    "id": 33,
    "userHandle": " PNfyQdC2cWaxtGiMZhLT9g1Lc9H2",
  },
];

const result = arr.reduce(
  (grouped, { id, ...obj }) => {
    let found = grouped[id];
    
    if (!found) {
      found = [];
      grouped[id] = found;
    }
    
    found.push(obj);
    
    return grouped;
  },
  {},
);

console.log(result);

Basically you must reduce on the array pushing the item into an array keyed by the id.

Rúnar Berg
  • 4,229
  • 1
  • 22
  • 38
1

Similar but slightly different approach without reduce:

const arr = [
  {
    "id": 34,
    "userHandle": "Aw8AUj1mPkON1Fd1s6LhkNETHfb2",
  },
  {
    "id": 34,
    "userHandle": "LrIwIx9I1xQBJ7aeCSrinpEaDP53",
  },
  {
    "id": 33,
    "userHandle": " PNfyQdC2cWaxtGiMZhLT9g1Lc9H2",
  },
];

const grouped = {};
arr.forEach((obj)=> {
  if(typeof grouped[obj.id] === 'undefined') {
    grouped[obj.id] = {id: obj.id, userHandle: [obj.userHandle]}
  }
  else {
    grouped[obj.id].userHandle.push(obj.userHandle);
  }
});
console.log(grouped);
farhodius
  • 510
  • 3
  • 8
  • this seems like actually best answer. I have a question tho, i get these results but somewhere i get undefined and somewhere these results (which is expected because i didint put my entire array here anyways my entire array has some objects without property id so ofc somewhere i get undefined how would i remove those results where its undefined? – MatkoMilic Jan 14 '21 at 23:20
  • basically how to remove from array everywhere where its ==undefined – MatkoMilic Jan 14 '21 at 23:23
  • Yeah, ether use `filter()` to clean your array up or have an extra `if` block within the loop that checks if `id` property defined. – farhodius Jan 15 '21 at 00:31