lundi 10 juin 2019

JavaScript: Create a function groupBy that accepts an array and a callback, and returns an object

My Objective is the following:

Create a function groupBy that accepts an array and a callback, and returns an object. groupBy will iterate through the array and perform the callback on each element. Each return value from the callback will be saved as a key on the object. The value associated with each key will be an array consisting of all the elements that resulted in that return value when passed into the callback.

The code below successfully executes:

function groupBy(array, inputFunc) {
    let obj = {};

  for(let i of array){
    let key = inputFunc(i);

    // QUESTION on line of code below: 
    console.log(obj[key])

    if(obj[key] === undefined){
      obj[key] = [];
    }
        obj[key].push(i)
  }
  return obj; 
}

// Uncomment these to check your work!
const decimals = [1.3, 2.1, 2.4];
const floored = function(num) { return Math.floor(num); };


console.log(groupBy(decimals, floored)); // should log: { 1: [1.3], 2: [2.1, 2.4] }

But I'm a bit confused by the code. Specifically, when I do:

console.log(obj[key])

the above line of code appears to return:

undefined
undefined
[ 2.1 ]
undefined

Why is it printing undefined? Where is that coming from?

Because I do not understand where the undefined is coming from, I don't comprehend why the if statement is needed.

Aucun commentaire:

Enregistrer un commentaire