Search code examples
javascriptarrayschartsnormal-distribution

Javascript: how to sort an array for a normal distribution chart?


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?


Solution

  • 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 array
    • array.reverse() reverses the sorted array
    • slice(1) to remove the duplicate max value from the reversed array

    Note: 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.