dnfuller
10/23/2018 - 11:02 PM

Node number array sorter

Node.js number array sorter, using process.argv

// Create an application that takes in a series of numbers then sorts them.
// Feel encouraged to use Stack or Google to find the "sort" code.
// ===============================================

// Grab all of the command line arguments from Node.
var nodeArg = process.argv;

// Create an array that will hold all of the numbers (excluding the path and node command)
var numArray = [];

// Create a for-loop that starts with **2** so we skip the path and node command from the command line
// Use this for loop to build an array of numbers.
for (var i = 2; i < nodeArg.length; i++) {

  // Then "push" each of these numbers to the numArray.
  // Convert these numbers to "floats"; otherwise node will treat the input as strings
  numArray.push(parseFloat(nodeArg[i]));

}

// Then print the original numbers
console.log(numArray);

// Then print the sorted numbers by making use of a JavaScript sort function for numbers.
console.log(numArray.sort(sortNums));

// -----------------------------------------------

// This function is needed so the JavaScript sort function knows to sort in numeric order.
// (Default is to sort by alphabetic order).
// A quick Google + Stack search led us to a few different posts that all said the same.
// http://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly

function sortNums(a, b) {
  return (a - b);
}