Answers for "arr.sort()"

14

sorting array from highest to lowest javascript

// Sort an array of numbers 
let numbers = [5, 13, 1, 44, 32, 15, 500]

// Lowest to highest
let lowestToHighest = numbers.sort((a, b) => a - b);
//Output: [1,5,13,15,32,44,500]

//Highest to lowest
let highestToLowest = numbers.sort((a, b) => b-a);
//Output: [500,44,32,15,13,5,1]
Posted by: Guest on March-25-2020
20

JS array sort

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
Posted by: Guest on May-08-2021
52

sort javascript array

var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
Posted by: Guest on June-07-2020
13

javascript sort

var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]

var objs = [
  {name: "Peter", age: 35},
  {name: "Emma", age: 21},
  {name: "Jack", age: 53}
];

objs.sort(function(a, b) {
  return a.age - b.age;
}); // Sort by age (lowest first)
Posted by: Guest on May-21-2020
1

sort js

numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
Posted by: Guest on October-20-2020
1

arr.sort()

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); // for ascending
//another way for ascending
points.sort((a,b)=>{
  if(a>b){
      return 1
  }else if(a<b){
      return -1
  }else{
      return 0
  }
})
points.sort(function(a, b){return b - a}); // for descending
//another way for descending
points.sort((a,b)=>{
  if(a>b){
      return -1
  }else if(a<b){
      return 1
  }else{
      return 0
  }
})
Posted by: Guest on August-23-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language