I want to know how to retrieve data from the filter results where the filter process automatically stops if the conditions are not met in the next index when filtered. Here's an example of the code I made
var array = [1,2,3,4,5,100, 12,13,14]
var filterArr = array.filter((value, index) => {
var nextValue = array[index+1]
if(value >= 20 && nextValue <= 20){
return true
}
return false
})
//result that i want in filterArr variable is [1,2,3,4,5]
And the result I want is like this by ignoring the values 11, 12, 13, 14 because there is a value in the next index that is 100 which is greater than 20
Instead of using .filter() you can use .slice() with .findIndex(). First, you can find the index of the 100 element using the .findIndex(), and then using .slice() you can keep all elements up to but not including that index:
const array = [1, 2, 3, 4, 5, 100, 12, 13, 14];
const idx = array.findIndex((value, i) => value >= 20 && array[i+1] <= 20);
const res = idx > -1 ? array.slice(0, idx) : array.slice(); // res is a copy of the array, potentially with some items removed
console.log(res);
You could take a flag in a closure and omit the next values from filtering if flag is false.
const
array = [1, 2, 3, 4, 5, 100, 12, 13, 14],
result = array.filter(
(flag => value => flag && (flag = value <= 20))
(true)
);
console.log(result); // [1, 2, 3, 4, 5]