Skip to content Skip to sidebar Skip to footer

Javascript, Map Returns Undefined

So I have 24 'person' objects, which I created using 'names' array, so that 'dude' names are repeating; Next I made a function that compares some random numbers to object id-s, and

Solution 1:

You're overwriting the namesarr variable on each iteration of the loop. I think you meant to add to it on each pass, rather than overwrite it. To do that, you can use the array .concat method.

Then, finally, make sure to filter all the undefined values from the result before you return it.

var names = ["jim", "jack", "aaron", "hugh", "jeff", "cameron", "allen", "charlie"];
var len = 3,
  arr1 = [],
  counter = 1;


for (var i = 0; i < len; i++) {
  names.forEach(name => {
    arr1.push({
      id: counter,
      dude: name
    });
    counter++;
  });
}

console.log(arr1);

functioncheckName(nums) {
    var namesarr = [];
    for (var i = 0; i < arr1.length; i++) {
        namesarr = namesarr.concat(nums.map(function(num) {
            if(num === arr1[i].id) {
                return arr1[i].dude;
            }
        }));
    }
    return (namesarr.filter(Boolean));
};
console.log(checkName([1,3,6]));

Solution 2:

The result of map() is an array of all the returned values. If a function doesn't execute a return statement, it's equivalent to ending with return undefined.

In your second version, whenever the if condition fails, you don't execute return arr1[i].dude;, so it's returning undefined by default. It's as if you'd written:

namesarr = nums.map(function(num) {
  if (num === arr1[i].id) {
    return arr1[i].dude;
  } else {
    returnundefined;
  }
});

The other difference between your two versions of the code is that the second version reassigns namesarr each time through the for loop. So you're just printing the result of the last iteration.

The first version assigns it once before the loop, and adds to it only when the if condition succeeds, so you get the elements from all iterations.

Solution 3:

Your map function doesn't return something for all the items in the array (because of the if) so some values in the result array will be undefined.

Plus, your map is inside a loop that loops over arr1, so for each iteration of that loop, the array namesarr get overridden. So the map will be as if it was applied only for the last element in arr1, thus if nums contain N elements then namesarr will have at least N - 1undefined values in it (N - 1 if the last object of arr1 matches nums, N if not).

The problem is better solved using reduce instead of map:

functioncheckName(nums) {
    return arr1.reduce(function(namesarr, obj) {     // for each object obj in the array arr1if(nums.indexOf(obj.id) !== -1) {            // if the object's id is in the array nums
            namesarr.push(obj.dude);                 // then add the object's dude to the array namesarr
        }
        return namesarr;
    }, []);                                          // the empty array to initialize namesarr
}

Post a Comment for "Javascript, Map Returns Undefined"