Answers for "sort elements in array"

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
0

JavaScript Sorting Arrays

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();        // Sorts the elements of fruits
Posted by: Guest on February-27-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
-1

Sorting an Array

const fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.sort();        // Sorts the elements of fruits
Posted by: Guest on August-17-2021
-2

array sorting

/*
  Arrays Methods [Sort]
  - sort(Function [Opt])
  - reverse
*/

let myFriends = [10, "Sayed", "Mohamed", "90", 9000, 100, 20, "10", -20, -10];

console.log(myFriends);
console.log(myFriends.sort().reverse());
Posted by: Guest on July-14-2021

Code answers related to "sort elements in array"

Browse Popular Code Answers by Language