I need to create a function for filter and it must have 2 choices.
inBetween(a, b)
- which will return array between a
and b
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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With