I have to sort an array for a normal distribution chart, so its values must be sorted from the minimum value to the maximum value and then back to minimum, creating a curve.
Example:
Array:
[200, 300, 0, 100, 400]
How it must be sorted:
[0, 100, 200, 300, 400, 300, 200, 100, 0]
Any ideas of how to do this in Javascript?
You could do something like this using sort
, reverse
and slice
:
const array = [200, 300, 0, 100, 400]
const newArray = [...array.sort((a,b) => a - b), ...array.reverse().slice(1)]
console.log(newArray)
array.sort((a,b) => a - b)
sorts the arrayarray.reverse()
reverses the sorted arrayslice(1)
to remove the duplicate max value from the reversed arrayNote: This just generates a normal distribution array from the existing array by creating duplicate values as you requested. But if you want to just convert an array to normal distribution, without adding any elements, then take a look at @Nina's excellent answer.