I’m trying to sort an array of 6 integers in descending order(javascript) but keep matching values in their place as the other values are sorted. An example is posted below to help explain this problem:
Input: 4, 2, 5, 4, 7, 3
Output: 4, 7, 5, 4, 3, 2
Another Example with multiple matching values:
Input: 3, 4, 3, 4, 2, 8
Output: 3, 4, 3, 4, 8, 2
If there is no matching values:
Input:
6, 2, 9, 5, 3, 4
Output:
9, 6, 5, 4, 3, 2
First you would need to check whether if any values values match, and which values match. I’m not exactly sure how to do this in this context. I’m also not sure how to sort all the other values in the array other than the matching ones. Thanks in advance!
I tried running a for loop for the length of the array that checks every number to see whether there are any matches but this caused repeated values and doesn’t get any closer to the solution
2
Answers
You could use 2 maps to collect values and indices in 1 go to sort and push back to the original array:
Use Javscript’s Array.prototype.sort function. It makes sorting alot easier.
The callback gets passed two values,
a
andb
, that need to be compared. The number you return decides where the values need to go:a
should come beforeb
a
should come afterb
NaN
means thata
andb
are considered equal.Here is an example showing how to use the sort function: