bdm bdm - 5 months ago 10
Javascript Question

passing new values correctly but also passing undefined into new array

I have declared a function called filter, taking an array and callback as arguments and passing only even numbers into the new array. The code works but it also passes in the un-even numbers as "undefined" (I am quoting it, not a string). What am I doing wrong?

function filter(array, callback) {
var output = [];
for(var i = 0; i < array.length; i++) {
output.push(callback(array[i]));
}
return output;
}

function isEven(elem) {
if (elem % 2 === 0)
return elem;
}

filter([0,1,2,3,4,5,6,7],isEven); -> [ 0,undefined,2,undefined,4,undefined, 6,undefined]

Answer

If you only want a filter, the callback should only return a boolean:

function filter(array, callback) {
  var output = [];
  for(var i = 0; i < array.length; i++)
    if(callback(array[i]))
      output.push(array[i]);
  return output;
}
function isEven(elem) {
  return elem % 2 === 0;
}
console.log(filter([0,1,2,3,4,5,6,7],isEven));

But if you want some mix of map and filter, just check if the mapped value is different than undefined before pushing it to the array.

function mapFilter(array, callback) {
  var output = [];
  for(var i = 0; i < array.length; i++) {
    var value = callback(array[i]);
    if(value !== undefined)
      output.push(value);
  }
  return output;
}
function isEven(elem) {
  if (elem % 2 === 0)
    return elem;
}
console.log(mapFilter([0,1,2,3,4,5,6,7],isEven));