How to Reorder An Array of Numbers in JavaScript

Sometimes we need to reorder an array of numbers so that the order goes from small to big or otherwise.

Logic

The logic of reorder an array of numbers is this:
  1. Find the min or max number in the array.
  2. Push this number into a new array.
  3. Delete this number.
  4. Continue the second and steps until there is no number in the original array.

Tools

 Here are some of the methods I use to make a reordering function:

  • Math.min() or Math.max() depending whether you want to start with the minimun or maximun number.
  • array.push is used to add number to the array with the target order, small to big or vise versa.
  • array.splice() is used to delete the pushed number to prevent multiple counting.
  • while loop is used to execute the process unitl all numbers are arranged.

Code

function reorder(arr){
   var newArr = [];
   while(arr.length != 0){
  	  var min = Math.min(...arr);
   	  var index = arr.findIndex(x=>x == min);
   	  newArr.push(min);
          arr.splice(index,1);
      };
   return newArr;    
};

Playground 

Type in the input with numbers seperated with commas and press "Reorder" button to reorder the array from small to big.


When do I need to reorder an array?

The counting of random numbers needs it. When a random number is created and counted, I need to reorder the created number in an array unless order doesn't matter. But I think order matters in a counting random number problem because otherwise we can't see the relationship between each random numeber
Counting of random numbers has something to do with doing statistics analysis when we need to see the distribution.
For example, when doing stock return analysis, we need to order the returns so that we see how often a return appears when investment dates are randomly selected. If returns array, the x-axis, is not in order, we can't visualize the result.

Comments

Popular posts from this blog

How to Make A Reusable Image Slideshow HTML Component With Vanilla JavaScript

HTML Tags and Inline CSS that Work In Plotly.js Title

How to Type Spaces In HTML Input And Display In the Browser