Rearranging array elements in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

JavaScript function that takes in an array of literals, arr, as the first and the only argument. This array contains some duplicates placed adjacently.

Our function should rearrange the elements of the array such that no two elements in the array are equal. Our function should return the rearranged array, given that it's guaranteed that there exists at least one possible way of such arrangement.

For example, if the input to the function is −

const arr = [7, 7, 7, 8, 8, 8];

Then the output should be −

const output = [7, 8, 7, 8, 7, 8];

Output Explanation:

There may be other correct possible rearrangements as well.

Example

The code for this will be −

const arr = [7, 7, 7, 8, 8, 8];
const rearrangeArray = (arr = []) => {
   const map = arr.reduce((acc, val) => {
      acc[val] = (acc[val] || 0) + 1 return acc;
   }, {});
   const keys = Object.keys(map).sort((a, b) => map[a] - map[b]);
   const res = [];
   let key = keys.pop();
   for(let i = 0; i < arr.length; i += 2){
      if(map[key] <= 0){
         key = keys.pop();
      };
      map[key] -= 1;
      res[i] = Number(key);
   };
   for(let i = 1; i < arr.length; i += 2){
      if(map[key] <= 0){
         key = keys.pop();
      };
      map[key] -= 1;
      res[i] = Number(key);
   };
   return res;
};
console.log(rearrangeArray(arr));

Output

And the output in the console will be −

[ 8, 7, 8, 7, 8, 7 ]
raja
Published on 07-Apr-2021 07:56:11
Advertisements