Skip to content Skip to sidebar Skip to footer

How To Find The Groups Of Consecutive Elements In Array

I have to cluster the consecutive elements from a array. Considering the following example. ts = [1, 2, 3, 5, 6,9] I want to find the groups of consecutive elements in array outpu

Solution 1:

with for-loop and temp array we can build result

const ts = [1, 2, 3, 5, 6, 9];

const res = [];
const temp_arr = [ts[0]];

for (let i = 1; i < ts.length; i++) {
  if (ts[i] !== ts[i - 1] + 1) {
    res.push([...temp_arr]);
    temp_arr.length = 0;
  } 
  temp_arr.push(ts[i]);
}
res.push([...temp_arr]);

console.log(res);

Solution 2:

Try following code.

const ts =  [1, 2, 3, 5, 6,9];
const arr =  ts.sort();
let groupedArr = [];
let lastElement = arr[0] - 1;
let tempArr = [];

arr.map((x) => {
    if (lastElement+1 === x) {
        tempArr.push(x);
        lastElement = x;
    } else {
        groupedArr.push(tempArr);
        tempArr = [x];
        lastElement = x;
    }
});
groupedArr.push(tempArr);

console.log(JSON.stringify(groupedArr))

Solution 3:

const ts = [1, 2, 3, 5, 6, 9];

functionfindConsecutiveElems(input) {
    if(input.length <= 0) 
    return [];

    let res  = [];
    let currentList = [];
    
    input.forEach(val => {
        if (currentList.length === 0) {
            currentList.push(val);
        }
        else {
            //if it's the next oneif(currentList[currentList.length-1] + 1 === val) {
                currentList.push(val);
            }
            // if not the next one else {
                res.push(currentList);
                currentList = [];
                currentList.push(val);
                // if is the last one if(val === input[input.length-1]) {
                    res.push(currentList);
                    currentList = [];
                }
            }   
        }
    })

    return res;
}

let res = findConsecutiveElems(ts);

console.log(res);

Post a Comment for "How To Find The Groups Of Consecutive Elements In Array"