en.javascript.info icon indicating copy to clipboard operation
en.javascript.info copied to clipboard

Bug in solution of this task: https://javascript.info/array-methods#create-keyed-object-from-array

Open dubeyrahul opened this issue 1 year ago • 0 comments

There's a bug in the solution posted in this task. The task requires us to group objects by id and put the grouped objects in an array keyed by id. The solution posted is:

function groupById(array) {
  return array.reduce((obj, value) => {
    obj[value.id] = value;
    return obj;
  }, {})
}

However, this does not work when there are items in array with same id. To accomplish the task correctly, the solution should be:

function groupById(array) {
  return array.reduce((obj, value) => {
    obj[value.id] == undefined ? obj[value.id] = [value] : obj[value.id].push(value);
    return obj;
  }, {})
}

dubeyrahul avatar Oct 02 '24 16:10 dubeyrahul