Reputation: 29
There is a sorted array with numbers, for example:
const array = [100, 400, 700, 1000, 1300, 1600]
There is a function that takes two arguments as input:
function foobar(min, max) {}
The function should return the numbers from the array, starting with the first value that is >=
to the min
and ending with the last value that is >=
to the max
.
foobar(250, 1010) // returns [400, 700, 1000, 1300]
foobar(0, 15) // returns [100]
How to implement this using modern JS?
array.filter((num) => {
return num >= min && num <= max
})
Always loses the last number. 🤔
Upvotes: 0
Views: 440
Reputation: 7249
This is a perfect use-case of for...of
loop.
const array = [100, 400, 700, 1000, 1300, 1600];
function foobar(array,min,max) {
let new_array = [];
for (let val of array) {
if(min<=val && val<=max) {
new_array.push(val);
} else if(val>max) {
new_array.push(val);
break;
}
}
return new_array;
}
console.log(foobar(array,0,15)); // outputs [100]
console.log(foobar(array,250,1010)); // outputs [400, 700, 1000, 1300]
It's simple, follows conventional programming paradigm and it traverses the array only once.
Upvotes: 2
Reputation: 10130
Here's one way
const array = [100, 400, 700, 1000, 1300, 1600];
const foobar = (min, max) => {
// get the lowest number higher than or equal to max
const lowestHigh = array.find(n => (n >= max));
const within = val => (val >= min && val <= lowestHigh);
return array.filter(within);
};
console.log( foobar(0, 150) );
console.log( foobar(400, 1500) );
Upvotes: 1