Sort the array and group all the identical (duplicate) numbers into their separate subarray in JavaScript


In this problem, we have to group all the duplicate data in the array by making their subarray. After making the subarray we have to arrange them in a sorted order. This problem can be solved by searching techniques of data structures.

Understanding the Problem

So for solving this problem, we will use javascript’s reduce() method in two ways. The reduce method is an iterative method which uses a reducer function to iterate through all the items in the array.

So by checking one by one we will keep track of all the elements and keep it in a separate variable and group them after iterating all the elements from the array.

Algorithm - First Method

Step 1: Define all the necessary variables in this step. In our case we have created an array with the name ‘arrayData’.

Step 2: Now to iterate all the items of the array we will use the reduce function of javascript and use two pointers to get the position of each item. The pointers are named as prevItem and currentItem. If the prevItem is the same as the currentItem then add them in a subarray otherwise in a new array.

Step 3: Now put all the values In object form and assign the newly created array in the sameObjToArray variable.

Step 4: After grouping all the duplicate elements, return the result and show the output using the console.

Example

//Define array of duplicate elements in it
const arrayData = [2,3,8,9,2,3,5,4,8,9,2,3,7,5];

//define a variable to check same items
const sameObj = arrayData.reduce(
   (prevItem, currentItem) => ({
     ...prevItem,
     [currentItem]: [...(prevItem[currentItem] || []), currentItem],
   }),
   {}
  );
  
const sameObjToArray = Object.values(sameObj);

// console the output
console.log("After grouping identical elements");
console.log(sameObjToArray);

Output

After grouping identical elements
[ [ 2, 2, 2 ], [ 3, 3, 3 ], [ 4 ], [ 5, 5 ], [ 7 ], [ 8, 8 ], [ 9, 9 ] ]

Algorithm - Second Method

Step 1: In the given problem, we will check duplicate elements of an array and make a group of them in a single array, so to implement this problem statement we will follow some guidelines. Firstly, we will create a function to check the identical elements and pass an array as an argument.

Step 2: We must first sort the provided array using the sort() method if it is not already sorted. We sort the provided array in ascending order in this step. After placing an order, grouping will be simple, and you can then put the item into the new array.

Step 3: As was said in prior steps, the array has now been sorted. In order to build a subarray, we require an empty array of the original array of components. and as a result give it its name.

Step 4: After step 1, 2 and 3 the step is to iterate all the elements of the input array so we will initialize a for loop with the length of array.

Step 5: In the for loop, check the value of elements if they are identical then push it in the same subarray. Otherwise push it in the new subarray.

Step 6: In this step, declare the input array data to which we have to pass in the above function.

Step 7: In the last step define another variable to call the above mentioned function and pass a declared array in it. And to print the result, console the output.

Example

// define a function to check duplicate numbers
function groupDuplicateNumbers(array) {
  array.sort((a, b) => a - b); 

  // declare empty array
  const result = [[]]; 

 // initialize a for loop to iterate all the elements
  for (let i = 0; i < array.length; i++) {
   // if-else condition to check elements are same
   if (array[i] === array[i-1]) {
     result[result.length - 1].push(array[i]); 
   } else {
     result.push([array[i]]); 
   }
  }

  return result.slice(1); 
}

//define array and call function
const array =  [151,221,330,151,221,330,414,202,202,414];
const finalGroup = groupDuplicateNumbers(array); 
console.log("The group of identical items in array:")
console.log(finalGroup); 

Output

The group of identical items in array:
[
  [ 151, 151 ],
  [ 202, 202 ],
  [ 221, 221 ],
  [ 330, 330 ],
  [ 414, 414 ]
]

Complexity

To calculate the complexity, we have to check the array size and the function. So in our program we are using an array of n elements and there is a sameObj function, which is iterating all the items and checking their occurrences. After checking repeated items we are putting it in a subarray to create the combination of a new array of subarray. So basically the time taken to complete execution of this program is O(n), because of n elements of the array.

Conclusion

So after solving this problem we have learned to remove or separate duplicate elements of an array. So this method will reduce the redundancy of data and also reduce the memory space to save the data. In the end we have concluded that the time complexity of this algorithm is O(n).

Updated on: 18-Aug-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements