Combining the identical entries together in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[ [ 234, 234 ], [ 65, 65 ], [ 2, 2 ] ]
raja
Published on 20-Oct-2020 15:18:57
Advertisements