Home > Mobile >  Group the consecutive numbers from an array with series of numbers which are greater than 2 into sub
Group the consecutive numbers from an array with series of numbers which are greater than 2 into sub

Time:11-12

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

CodePudding user response:

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 ?
                (
                    lastIdx = idx,
                    acc[acc.length - 1].push(current), 
                    acc
                )
                :
                (
                    lastIdx = idx,
                    [...acc, [current]]
                )
        ) : acc
    )
, [])

console.log(results);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related