Group matching element in array in JavaScript


In the given problem statement we are asked to make a group matching element in an array with the help of javascript functionalities. As we talk about grouping elements of an array we usually use the reduce method.

What is the reduce() function in JavaScript ?

Let's understand the working of a reduce function in JavaScript.

In javascript, the built−in method reduce() is used to iterate on all the elements of an array. This method accumulates an item based on every element of the array, which basically takes two arguments. First argument is an accumulator and the second value is a current value. The reduce function is called for each element of the array and gives the new value of the accumulator.

Following is the syntax to define reduce in JavaScript : −

const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
console.log(sum);  

Output

15

Understanding the Logic

The code takes an input array arr and will group all the items that are the same to one another. Then it will return an array of arrays with each inner array keeping the indices of all duplicate elements in the array.

Algorithm

Step 1 : At the beginning, we will start creating an array with some duplicate values in it.

Step 2 : Now we will use the reduce function on the created array to make a group of the elements.

Step 3 : After the second step, Inside the reducer function we will check if the last item in the array is the same as the current element.

Step 4 : Now forwarding, This step will identify that if the last element is not identical as the current element and add a new sub array to the array of sub arrays.

Step 5 : After checking above mentioned conditions, push the current item to the last sub array in the array of sub arrays.

Step 6 : Now show the updated object with the sub arrays.

Step 7 : Now access the sub arrays in the object returned by the reducer function and then assign it to the variable groupedArray.

Step 8: Show the output with the help of groupedArray variable.

Example 

// define array of containing some repeated items
const array = ['A','A','A','A','D','E','E','F','H','H','H','L','M','S','S','U','Y','Y'];

    // create new array to make groups
    const groupedArray = array.reduce((item, index) =>{
        if (typeof item.last === 'undefined' || item.last !== index) {
            item.last = index;
            item.array.push([]);
        }
        item.array[item.array.length - 1].push(index);
        return item;
    }, {array: []}).array;

//console the output    
console.log(groupedArray);

Output

[
    [ 'A', 'A', 'A', 'A' ],
    [ 'D' ],
    [ 'E', 'E' ],
    [ 'F' ],
    [ 'H', 'H', 'H' ],
    [ 'L' ],
    [ 'M' ],
    [ 'S', 'S' ],
    [ 'U' ],
    [ 'Y', 'Y' ]
]

The code given above is the most straightforward method that comes to mind on reading the problem statement, but if you grasp the theory behind it, you can simplify and adapt it to make the most efficient use of time and space.

In the above code we have declared a reduce function taking in the accumulator and current element as input. Then we go step by step , following first to check the if statements and push it to the gourpedArray. In the last we have got the resultant array of sub arrays.

In the code, the groupedArray object is used to store the resultant sub arrays for the given array ['A','A','A','A','D','E','E','F','H','H','H','L','M','S','S','U','Y','Y']. The function returns the output as the sub array of similar elements of the array.

Time Complexity

Time complexity: The above code only executes once and it iterates all the elements of the array in O(n) time. Then the inner loop of the reducer function has complexity of O(1) for every iteration. This is because we are grouping items and not doing any other task. So the overall time complexity for this code will be O(n).

Space complexity: To store the sub arrays a new array is required, because we are only storing pointers to the input elements. So the size of the sub arrays will depend on the input data given. The space complexity will be O(n).

Conclusion

This is the way we can get the final result for the above problem statement. The most easy and reliable method to group the duplicate elements for an array that contains repeated items in JavaScript. It uses the reduce method to iterate through the input array and create sub−arrays of matching elements. Both time complexity and space complexity will be of O(n).

Updated on: 23-Aug-2023

242 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements