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

209
Views
How to group all contiguous even numbers into a 2D array?

I've the following array of numbers:

[10, 12, 23, 17, 14, 15, 50, 72, 26, 33]

And I want to group all even numbers that appear together, as below:

[ [ 10, 12 ], [ 14 ], [ 50, 72, 26 ] ]

I'm able to filter out the even numbers, but I'm unable to group the contiguous ones together. I think reduce can be used here, but I'm unable to understand how, any help is highly appreciated.

const nums = [10, 12, 23, 17, 14, 15, 50, 72, 26, 33];
const result = nums.map((n, i) => (n % 2 === 0 ? [n] : []));

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

0

You can use Array.prototype.reduce

For every number that is even, do the following:

  1. Push an empty array into the resultant array if the last number was not even (i.e. it was odd).

  2. Get the last group in the resultant array using Array.prototype.at and then push the current number into this group.

const 
  nums = [10, 12, 23, 17, 14, 15, 50, 72, 26, 33],
  result = nums.reduce((res, num, i) => {
    if (!(num & 1)) {
      if (!i || nums[i - 1] & 1) {
        res.push([]);
      }
      res.at(-1).push(num);
    }
    return res;
  }, []);

console.log(result);

Note: I've used the Bitwise AND (&) operator to check if a number is even or odd, you could also use the Remainder operator (%).

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!