Skip to content Skip to sidebar Skip to footer

Higher Order Function Javascripts

I'm trying to understand better and start coding JS with higher order functions. Below is just a practice I'm doing, and I want to output an array of numbers * 2. function each(col

Solution 1:

I think this will work for you:

// Let's call this what it isfunctiongetNumbersFromArray(collection, callback) {
    var arr = [],
        i = 0;

    for (; i < collection.length; i++) {
        // Check if isNumber and do mutliplication hereif (callback(collection[i])) {
            arr.push(item * 2);
        }
    }

    return arr;
}

// Make isNumber actually return a booleanfunctionisNumber(item) {
    returntypeof item === "number";
}

// call console.log()console.log(getNumbersFromArray([1, 2, 3, 4, "String"], isNumber)); 

Solution 2:

no output is showing because neither of your functions return anything.

here, i'd have your callback just apply the multiplication and return that value, then push to an array in your each function

functioneach(collection, callback) {
  var arr = [];
  for(var i = 0; i < collection.length; i++) {
      var result = callback(collection[i])
      if (typeof result !== 'undefined') {
        arr.push(callback(collection[i]));
      }
    }
  return arr
}

functionisNumber(item) {
    if (typeof item === "number") {
      return item * 2;
    }
}

Post a Comment for "Higher Order Function Javascripts"