- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Group a sorted array based on the difference between current and previous elements in JavaScript
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 ] ]
- Related Articles
- How to get index in a sorted array based on iterator function in JavaScript?
- Manipulate Object to group based on Array Object List in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Maximum difference between the group of k-elements and rest of the array in C
- How to group objects based on a value in JavaScript?
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- Sort array based on another array in JavaScript
- Filter array based on another array in JavaScript
- How to add the previous set of elements on the stack to the current set in jQuery?
- Search and update array based on key JavaScript
- Sorting Array based on another array JavaScript
- Reorder array based on condition in JavaScript?
- Compress array to group consecutive elements JavaScript
- Sort array based on min and max date in JavaScript?

Advertisements