Jack
0
Q:

javascript sort function

const unsorted = ['d', 'd', 'h', 'r', 'v', 'z', 'f', 'c', 'g'];
const sorted = unsorted.sort();

console.log(sorted);
//["c", "d", "d", "f", "g", "h", "r", "v", "z"]


const unsortedNums = [45, 56, 3, 3, 4, 6, 7, 45, 1];
const sortedNums = unsortedNums.sort((a, b) => {
	return a - b;
});

console.log(sortedNums);
//[1, 3, 3, 4, 6, 7, 45, 45, 56]
3
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
7
const sort = arr => arr.sort((a, b) => a - b);
//By default,the sort() function sorts values as strings.Fix this by providing a compare function.
// Example
sort([1, 5, 2, 4, 3]);      // [1, 2, 3, 4, 5]
4
var numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers);

// [1, 2, 3, 4, 5]
3
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;
                               });
0
let numbers = [5, 2, 8, 1, 4, 6, 3, 7]
numbers.sort() // sorts the numbers ascending: [1, 2, 3, 4, 5, 6, 7, 8]
-1

New to Communities?

Join the community