Group a sorted array based on the difference between current and previous elements in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose we have an array of Integers sorted in an increasing order like this −

const arr = [ 1, 2, 3, 5, 6, 7, 10, 12, 17, 18];

We are required to write a JavaScript function that takes in one such array. The function should group the array in such a way so that −

  • Elements within a group have a difference of 1 or less

  • Each group element should have more than one element to be considered valid

Based on the above conditions, the expected output would be −

const output = [
   [1, 2, 3],
   [5, 6, 7],
   [17, 18]
];

Example

The code for this will be −

const arr = [ 1, 2, 3, 5, 6, 7, 10, 12, 17, 18];
const groupNear = (arr = []) => {
   const res = [];
   for (let ind = 0; ind < arr.length; ind++) {
      let value = arr[ind];
      if (arr[ind − 1] + 1 === value) {
         res[res.length − 1].push(value);
      } else if (value + 1 === arr[ind + 1]) {
         res.push([value]);
      };
   };
   return res;
};
console.log(groupNear(arr));

Output

And the output in the console will be −

[ [ 1, 2, 3 ], [ 5, 6, 7 ], [ 17, 18 ] ]
raja
Published on 25-Nov-2020 11:36:40
Advertisements