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);
You can use Array.prototype.reduce
For every number that is even, do the following:
Push an empty array into the resultant array if the last number was not even (i.e. it was odd).
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 (%).