Reputation: 370
I'm trying to solve an exercise where I have to sort an array. I have to sort it in a particular way: from the biggest number to the smallest number, from the lowest numbers of numbers to the highest numbers of numbers.
Example: if the given array is
[1, 6, 12, 66, 66, 66, 44, 44, 44, 34, 34, 4, 4, 4, 5, 5, 5, 5, 122, 122, 122, 122]
the result should be:
[12, 6, 1, 34, 34, 66, 66, 66, 44, 44, 44, 4, 4, 4, 122, 122, 122, 122, 5, 5, 5, 5]
My idea was to measure the length of the same elements in the array and sort them from lowest to highest, and then sort the biggest to the smallest number. I cannot even get past the point of comparing the elements with one another, let alone the length of them. Is it normal to be that difficult to compare elements with each other? This is just one of the hundreds of different attempts to compare.
function sortIt(arr){
let result = [];
for (let i = 0; i < arr.length; i++) {
for (let j = arr.length - 1; j <= 0; j--) {
if (arr[j] === arr[i]) {
result.push(arr[i]);
}
}
}
console.log(result)
}
Upvotes: 0
Views: 67
Reputation: 413727
I think you'll need to transform the array into an array of objects so you can keep the original values and the occurrence counts. Then you can sort that on both keys, strip out only the values afterwards:
const array = [1, 6, 12, 66, 66, 66, 44, 44, 44, 34, 34, 4, 4, 4, 5, 5, 5, 5, 122, 122, 122, 122];
function sortIt(arr) {
let oarr = array.reduce((accum, v) => (accum[v] = accum[v] ? accum[v]+1 : 1, accum), {});
let combined = array.map(v => ({ value: v, count: oarr[v] }));
return combined.sort((a, b) => a.count - b.count || b.value - a.value).map(o => o.value);
}
console.log(sortIt(array));
In that code, first oarr
is constructed to count the occurrences of each value. The second step creates a new array of objects with properties for the original value and the count. The last step performs the sort and then builds an array from only the values in the sorted result.
The sort comparison compares the value counts first, which is what your expected result requires. In general, when you have to sort on multiple "keys", the correct approach is to use a comparison function that works from the most important key to the least important key. Here, that's done by this function:
(a, b) => a.count - b.count || b.value - a.value
If the counts are the same, then a.count - b.count
will return 0, so the ||
evaluation will proceed to the value comparison. If the counts, are different, however, then that's the result of the comparison because the values don't matter.
Upvotes: 2