- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Check if some elements of array are equal JavaScript
We have an array of numbers that have got some redundant entries, our job is 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 = [1, 3, 3, 1]; //then the output should be: const output = [[1, 1], [3, 3]];
We will use a HashMap to keep a track of the elements already occurred and iterate over the array using a for loop, the code for this will be −
Example
const arr = [1, 3, 3, 1]; 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
The output in the console will be −
[ [ 1, 1 ], [ 3, 3 ] ]
Advertisements
To Continue Learning Please Login
Login with Google