Can someone suggest some better way of writing this Javascript code

Viewed 45

I am given an input array need to convert to output array (it's consecutive array in the output array.)

var input = [1, 3, 4, 5, 8, 9, 15, 20, 21, 22, 23, 24, 25, 26, 40];
var output = [[1], [3, 4, 5], [8, 9], [15], [20, 21, 22, 23, 24, 25, 26], [40]];

I am able to achieve this by:

let t = 0;
let tArr = []
const a = [];
input.map(i => {
  if (i-t === 1) {  
    tArr.push(i);
  } else {
    a.push(tArr);
    tArr = [];
    tArr.push(i)
  }
  t = i;
});
a.push(tArr);
console.log("final", a)

Can someone suggest a cleaner code or if this could be optimized.

1 Answers

You could reduce the array by looking at the index or ar the former value and compare to the actual value.

var input = [1, 3, 4, 5, 8, 9, 15, 20, 21, 22, 23, 24, 25, 26, 40],
    result = input.reduce((r, v, i, a) => {
        if (!i || a[i - 1] + 1 < v) {
            r.push([v]);
        } else {
            r[r.length - 1].push(v);
        }
        return r;
    }, []);

console.log(result);

Related