order array by value js code example

Example 1: javascript sort array with objects

var array = [
  {name: "John", age: 34},
  {name: "Peter", age: 54},
  {name: "Jake", age: 25}
];

array.sort(function(a, b) {
  return a.age - b.age;
}); // Sort youngest first

Example 2: how to sort an array by value in javascript

//ascending order
arr.sort(function(a, b){return a-b});
arr.sort((a, b) => a - b);
//descending order 
arr.sort(function(a, b){return b - a});
arr.sort((a, b) => b - a);

Example 3: sort javascript array

var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)

Example 4: put array in alphabetical order

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Tags:

Cpp Example