admin管理员组

文章数量:1333451

I need to create a function for filter and it must have 2 choices.

  1. inBetween(a, b) - which will return array between a and b
  2. inArray([...]) - which will return an array of items that match with filtering array.

Something like this:

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

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6
console.log( arr.filter(f(inArray([1, 2, 10]))) ); // 1,2

I tried this function:

function f(item) {
  let result = [];

  function inBetween(from, to){
    if (item >= from && item <= to){
      result.push(item);
    }
  }

  function inArray(array){
    if (array.indexOf(item) >= 0){
      result.push(item);
    }
  }

  return result;
}

But I don't know how to attach my function into filter. It gives this error:

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6

ReferenceError: inBetween is not defined

Is it somehow possible?

I need to create a function for filter and it must have 2 choices.

  1. inBetween(a, b) - which will return array between a and b
  2. inArray([...]) - which will return an array of items that match with filtering array.

Something like this:

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

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6
console.log( arr.filter(f(inArray([1, 2, 10]))) ); // 1,2

I tried this function:

function f(item) {
  let result = [];

  function inBetween(from, to){
    if (item >= from && item <= to){
      result.push(item);
    }
  }

  function inArray(array){
    if (array.indexOf(item) >= 0){
      result.push(item);
    }
  }

  return result;
}

But I don't know how to attach my function into filter. It gives this error:

console.log( arr.filter(f(inBetween(3, 6))) ); // 3,4,5,6

ReferenceError: inBetween is not defined

Is it somehow possible?

Share Improve this question asked Sep 28, 2019 at 17:25 Robert HovhannisyanRobert Hovhannisyan 3,3616 gold badges24 silver badges50 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 12

array.filter() requires a function. If you want to pre-bind some parameters, you'll need a function that returns a function. In this case, both inBetween and inArray should return functions.

So it should be:

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

function inBetween(min, max) {
  return function(value) {
    // When this is called by array.filter(), it can use min and max.
    return min <= value && value <= max
  }
}

function inArray(array) {
  return function(value) {
    // When this is called by array.filter(), it can use array.
    return array.includes(value)
  }
}

console.log( arr.filter(inBetween(3, 6)) )
console.log( arr.filter(inArray([1, 2, 10])) )

In this case, min, max, and array close over the returned function such that when array.filter() calls the returned function, it has access to those values.


Your inArray() functionality is already implemented by the native array.includes().

本文标签: Array filter function with multiply choices using closureJavascriptStack Overflow