Home > Net >  Filter numbers between Array with Parameter Function
Filter numbers between Array with Parameter Function

Time:10-01

I am trying to work with Arrays and .filter() function. I need to filter between parameters on a function to get it to the correct output. I can't seem to get my NPM test to pass. I can see the output seems correct, but the error I am getting is [object Array] is not a function at Array.filter Does anyone know where I am going wrong?

here is the code:

function betweenArray(c, d){
    
    let filterNumbers = arr.filter(function(currentElement) {
        if (currentElement >= c && currentElement <= d)
        return currentElement 
    })

    return filterNumbers
}

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(arr.filter(betweenArray(4, 10))); // 2, 3, 4, 5, 6, 7

CodePudding user response:

So, Array.filter takes a function that should return either true or false (i.e. a predicate function). If the function returns true the item is projected into the resulting array. If the function returns false, it is omitted from the resulting array.

You want a function that creates this predicate function.

Using arrow function notation, you can write this as:

const between = (min, max) => (v) => v >= min && v <= max;

Now you can use it:

const between = (min, max) => (v) => v >= min && v <= max;
let arr = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(arr.filter(between(-1, 3)));

Note:

The reason your predicate function (mostly) works

let filterNumbers = arr.filter(function(currentElement) {
    if (currentElement >= a && currentElement <= b)
        return currentElement 
})

is because any non-zero number is coerced to true and undefined is coerced to false.

Now let's try your version of the predicate function with a range that traverses zero and observe how it breaks:

const between = (min, max) => function(currentElement) {
  if (currentElement >= min && currentElement <= max)
    return currentElement // this value isn't `true`, it's a number
  // `undefined` implicitly returned here
}
let arr = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(arr.filter(between(-1, 3))); // no zero here!?!

Where did zero go? Can you figure out why it breaks?

CodePudding user response:

According to your description,you need to return a function instead of array instead

function between(a, b){
  
  return function(currentElement) {
        if (currentElement >= a && currentElement <= b)
        return currentElement 
     }
}
  • Related