

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Rearranging array elements in JavaScript
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 ]
- Related Questions & Answers
- Rearranging elements of an array in JavaScript
- Rearranging cards into groups in JavaScript
- Sorting Array Elements in Javascript
- Rearranging digits to form the greatest number using JavaScript
- Consecutive elements sum array in JavaScript
- Alternatingly combining array elements in JavaScript
- How to replace elements in array with elements of another array in JavaScript?
- Finding upper elements in array in JavaScript
- Accumulating array elements to form new array in JavaScript
- Absolute sum of array elements - JavaScript
- Compare array elements to equality - JavaScript
- Program to get maximum value of power of a list by rearranging elements in Python
- Remove elements from array using JavaScript filter - JavaScript
- Counting unique elements in an array in JavaScript
- Elements that appear twice in array in JavaScript
Advertisements