1

I need help with this JS callback function. I am trying to figure out how exactly callbacks work in JS.

--quick test code follows:

function debFilter(deb_array, fillCb){
    var filt_darr = [];
    for (var inx in deb_array) {
        filt_darr.push(fillCb(deb_array[inx]));
    }

  return filt_darr;

}
console.log(debFilter(savedInp, function(x) { if (x%2 == 0) { return x;}} ));  

Let's say my savedInp array contains [2,3,4,5,6,7,8,9] something like this. How do I make sure my callback returns only the even elements and not the odd ones? so my filt_darr would be [2,4,6...etc]. With the above test code I am getting [2,undefined,4,undefined,..etc]. I have tried with other similar conditions too with no avail. I just need to know how to tell JS not to 'push/return' something I dont need. Sorry if this is a beginner Q. Thanks for the help.

Shona
  • 261
  • 1
  • 4
  • 15
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Rune FS Mar 03 '16 at 18:47

2 Answers2

0

Iterate the array and then push evens into a new array:

 var a = [1,2,3,4,5];

 function getEvens(originalArray){

  var evens = [];
   for(var i = 0; i < originalArray.length; ++i){
     if(originalArray[i] % 2 === 0){
        evens.push(originalArray[i]);
     }
   }

   return evens;
 }
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

As you probably noticed, you are collecting every return value into your result array and your callback returns undefined for every odd. You could change your code to sth like

function debFilter(deb_array, fillCb){
        'use strict';

        var filt_darr = [],
            len = deb_array.length;

        for (var i = 0; i < len; i++) {
            if (fillCb(deb_array[i])) {
                  filt_darr.push(deb_array[i]);
            }
        }

        return filt_darr;
    }

By the way, ES 5 supports Array.prototype.filter which might be what you are looking for. There is also a polyfill that you can take some inspiration from.

macghriogair
  • 1,431
  • 10
  • 8