Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
Stop filtering the array if the condition is not met at the next index even though there is still data that can satisfy the next index

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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]

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!