Answers for ".sort function in javascript"

25

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
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

array sort js

arr = ['width', 'score', done', 'neither' ]
arr.sort() // results to ["done", "neither", "score", "width"]

arr.sort((a,b) => a.localeCompare(b)) 
// if a-b (based on their unicode values) produces a negative value, 
// a comes before b, the reverse if positive, and as is if zero

//When you sort an array with .sort(), it assumes that you are sorting strings
//. When sorting numbers, the default behavior will not sort them properly.
arr = [21, 7, 5.6, 102, 79]
arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
// b - a will give you the reverse order of the sorted items 

//this explnation in not mine
Posted by: Guest on October-07-2020
1

sorting in js

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;
}));
Posted by: Guest on February-25-2021
-1

sort function explained javascript

var sortedArray = myArray.sort(function(a,b){
                                   if (a.name < b.name)
                                      return -1;
                                   else if (a.name == b.name)
                                      return 0;
                                   else
                                      return 1;
                               });
Posted by: Guest on June-25-2020

Code answers related to ".sort function in javascript"

Browse Popular Code Answers by Language