- 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
Grouping identical entries into subarrays - JavaScript
Let’s say, we have an array of numbers that have got identical entries. We are required to write a function that takes in the array and groups all the identical entries into one subarray and returns the new array thus formed.
For example: If the input array is −
const arr = [234, 65, 65, 2, 2, 234];
Then the output should be −
const output = [[234, 234], [65, 65], [2, 2]];
We will use a hashmap to keep a track of the elements already occurred and iterate over the array using a for loop.
Example
Following is the code −
const arr = [234, 65, 65, 2, 2, 234]; const groupArray = arr => { const map = {}; const group = []; for(let i = 0; i < arr.length; i++){ if(typeof map[arr[i]] === 'number'){ group[map[arr[i]]].push(arr[i]); }else{ //the push method returns the new length of array //and the index of newly pushed element is length-1 map[arr[i]] = group.push([arr[i]])-1; } }; return group; } console.log(groupArray(arr));
Output
This will produce the following output in console −
[ [ 234, 234 ], [ 65, 65 ], [ 2, 2 ] ]
- Related Articles
- Combining the identical entries together in JavaScript
- Removing identical entries from an array keeping its length same - JavaScript
- Convert array into array of subarrays - JavaScript
- Convert 2d tabular data entries into an array of objects in JavaScript
- Complicated array grouping JavaScript
- Merging subarrays in JavaScript
- Explain Grouping operator in JavaScript.
- Grouping array values in JavaScript
- Grouping nested array in JavaScript
- Subarrays product sum in JavaScript
- Grouping data to monthwise in JavaScript
- Explain the basis for grouping organisms into five kingdoms.
- Sort the array and group all the identical (duplicate) numbers into their separate subarray in JavaScript
- Largest sum of subarrays in JavaScript
- All possible odd length subarrays JavaScript

Advertisements