0

i am wonder what this line in code do:

(result[obj[key]] = result[obj[key]] || []).push(obj);

What it exactly means? If x = x or [] add object to the list?

Whole code with output:

const people = [
  {
    name: "Rohan",
    age: 18
  },
  {
    name: "Mohan",
    age: 19
  },
  {
    name: "Shawn",
    age: 20
  },
  {
    name: "Michael",
    age: 21
  },
  {
    name: "David",
    age: 22
  },
];

let groupBy = (array, key) => {
  return array.reduce((result, obj) => {
    (result[obj[key]] = result[obj[key]] || []).push(obj);
    return result;
  }, {});
};

console.log(groupBy(people, "age"));

Output:

    {
      '18': [ { name: 'Rohan', age: 18 } ],
      '19': [ { name: 'Mohan', age: 19 } ],
      '20': [ { name: 'Shawn', age: 20 } ],
      '21': [ { name: 'Michael', age: 21 } ],
      '22': [ { name: 'David', age: 22 } ]
    }
deceze
  • 510,633
  • 85
  • 743
  • 889
mkl1337
  • 23
  • 5
  • 1
    What *do* you understand about this code? – Scott Hunter May 27 '21 at 12:47
  • 1
    This is a way to null coalesce using || operator. Here is a more extensive explanation: https://stackoverflow.com/questions/476436/is-there-a-null-coalescing-operator-in-javascript – SnowGroomer May 27 '21 at 12:49
  • 1
    `result[obj[key]] = result[obj[key]] || []` is a "trick" to read the value of `result[obj[key]]` and if it doesn't exist yet, initialize it with an empty array (and use that). It could also have been written as `if (!result[obj[key]]) { result[obj[key]] = []; } result[obj[key]].push(obj)`. – Felix Kling May 27 '21 at 12:51
  • _“`If x = x or []`”_ - it effectively means `x = (x or [])`. Go read up on [Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence), that will help you better understand stuff like this in the future. – CBroe May 27 '21 at 12:52
  • This can be shortened now and written as `result[obj[key]] ||= []` using [Logical OR assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment) – adiga May 27 '21 at 13:20

2 Answers2

3

(result[obj[key]] = result[obj[key]] || []).push(obj);

This is a shortcut of:

if(result[obj[key]]){
   result[obj[key]] = result[obj[key]];
}else{
   result[obj[key]] = [];
}

result[obj[key]].push(obj);
0

This code result[obj[key]] || [] this code is used to add dynamic keys. If you remove || [] you will get an error saying Cannot push value of undefined because you want to add new keys.

As you can see in your response object.

{
   '18': [ { name: 'Rohan', age: 18 } ],
    '19': [ { name: 'Mohan', age: 19 } ],
    '20': [ { name: 'Shawn', age: 20 } ],
    '21': [ { name: 'Michael', age: 21 } ],
    '22': [ { name: 'David', age: 22 } ]
}
Himanshu Saxena
  • 340
  • 3
  • 13