# Sorting array according to increasing frequency of elements in JavaScript

We are required to write a JavaScript function that takes in an array of literals as the first and the only argument.

The array is likely to contain many repeating values. Our function should sort the array such that the values that are unique or that have the least frequency are placed before the ones that have the most.

For example −

If the input array is −

const arr = [4, 7, 3, 5, 5, 4, 7, 9, 2, 1, 5, 7, 5, 5, 9];

Then the output array should be −

const output = [
3, 2, 1, 9, 9, 4,
4, 7, 7, 7, 5, 5,
5, 5, 5
];

## Example

Following is the code −

const arr = [4, 7, 3, 5, 5, 4, 7, 9, 2, 1, 5, 7, 5, 5, 9];
const sortByNumbers = (arr = []) => {
const map = {};
const res = [];
for (let i = 0; i < arr.length; i++) {
map[arr[i]] = map[arr[i]] || [0];
map[arr[i]][0]++;
map[arr[i]][1] = arr[i];
}
const sorted = Object.values(map).sort((a, b) => {
if (a[0] === b[0]) {
return b[1] - a[1];
}
return a[0] - b[0]
});
for (let i = 0; i < sorted.length; i++) {
const [freq, num] = sorted[i]
for (let j = 0; j < freq; j++) {
res.push(num);
}
}
return res;
};
console.log(sortByNumbers(arr));

## Output

Following is the console output −

[
3, 2, 1, 9, 9, 4,
4, 7, 7, 7, 5, 5,
5, 5, 5
]

Updated on: 19-Jan-2021

260 Views