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

149
Views
Group the consecutive numbers from an array with series of numbers which are greater than 2 into subarrays using javascript

Given an array A = [1,2,3,5,6,7,8,10,0,1,1,2,4,10,6,7,3], group the consecutive elements which are greater than 2 in to sub-arrays.

The desired output is result = [[2,3,5,6,7,8,10],[2,4,10,6,7,3]].

Example: A = [1,2,3,5,6,7,8,10,0,1,1,2,4,10,6,7,3]
Output: result = [[2,3,5,6,7,8,10],[2,4,10,6,7,3]]

Could anyone help with this question?

I have tried:

const a = [0, 1, 2, 5, 6, 9];
const result = a.reduce((acc, current) => 
   const lastSubArray = acc[acc.length - 1];
    
   console.log(`${acc}-${current}`)
  
   console.log(lastSubArray[lastSubArray.length - 1]);
   if (current >2 && lastSubArray[lastSubArray.length - 1]>2) {
      acc.push(current);
   }

   acc[acc.length - 1].push(current);
   console.log(acc);

   return acc;
}, []);

console.log(result);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use a global variable to keep track of the indexes so that it's possible to detect when exists a gap between two numbers, which allows you to add another array. In combination, using ternary operators can make the code cleaner to test for conditions.

const arr = [1, 2, 3, 5, 6, 7, 8, 10, 0, 1, 1, 2, 4, 10, 6, 7, 3];
let lastIdx = -1
const results = arr.reduce((acc, current, idx) => 
     (
        current > 2 ? (
            lastIdx + 1 === idx && acc.length ?
                (
                    lastIdx = idx,
                    acc[acc.length - 1].push(current), 
                    acc
                )
                :
                (
                    lastIdx = idx,
                    [...acc, [current]]
                )
        ) : acc
    )
, [])

console.log(results);

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!