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.

Using HashMap Approach

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));
[ [ 1, 1 ], [ 3, 3 ] ]

Using Array.reduce() Method

A more modern approach using the reduce() method:

const arr = [2, 5, 2, 8, 5, 2];
const groupArrayReduce = arr => {
    return Object.values(arr.reduce((acc, curr) => {
        if(!acc[curr]) {
            acc[curr] = [];
        }
        acc[curr].push(curr);
        return acc;
    }, {}));
}
console.log(groupArrayReduce(arr));
[ [ 2, 2, 2 ], [ 5, 5 ], [ 8 ] ]

How It Works

The HashMap approach works by:

  1. Creating an empty map to track element positions and a group array for results
  2. For each element, checking if it already exists in the map
  3. If it exists, pushing to the existing subarray using the stored index
  4. If it doesn't exist, creating a new subarray and storing its index in the map

Comparison

Method Performance Readability Memory Usage
HashMap with for loop O(n) Good Moderate
Array.reduce() O(n) Excellent Slightly higher

Conclusion

Both approaches efficiently group identical array elements. The HashMap method provides fine control over grouping logic, while the reduce method offers cleaner, more functional programming style.

Updated on: 2026-03-15T23:18:59+05:30

430 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements