sort by number array javascript code example

Example 1: javascript sort by numerical value

// Sort an array of numbers based on numerical value.
let numbers = [23, 65, 88, 12, 45, 99, 2000]

let sortednumbers = numbers.sort((a, b) => a - b);
//=> [12, 23, 45, 65, 88, 99, 2000]

Example 2: javascript sort array smallest to largest

var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);

Example 3: sorting array of numbers in javascript

var arr = [23, 34343, 1, 5, 90, 9]

//using forEach
var sortedArr = [];
arr.forEach(x => {
    if (sortedArr.length == 0)
        sortedArr.push(x)
    else {
        if (sortedArr[0] > x) sortedArr.unshift(x)
        else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
        else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
    }
})
console.log(sortedArr);


// using sort method
console.log(arr.sort((a,b)=>{
    return a-b;
}));

Example 4: how to sort array least to greatest javascript stACK

function sortArray(array) {
  var temp = 0;
  for (var i = 0; i < array.length; i++) {
    for (var j = i; j < array.length; j++) {
      if (array[j] < array[i]) {
        temp = array[j];
        array[j] = array[i];
        array[i] = temp;
      }
    }
  }
  return array;
}

console.log(sortArray([3,1,2]));