Sorting Arrays

  • When sorting a srrays, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order.

Basic Number/Integer Sorting

Inpur

Outout

Basic String

Basic String Sorting


let freelance = ['Upwork', 'Freelancer', 'Truelancer', 'PeoplePerHour'];
freelance.sort();

console.log(freelance);

1
2
3
4
5
6

Basic arr of number sorting

const arr = [1,2,77, 15]

unction compare(a, b){
  if (a > b) return 1;
  if (b > a) return -1;

  return 0;
}

arr.sort(compare);
1
2
3
4
5
6
7
8
9
10

function compare(a, b){
  return a - b;
}

1
2
3
4
5
//aboce in arrow function

arr.sort((a, b) => a - b);


1
2
3
4
5

Sorting with map


// the array to be sorted
var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];

// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
  return { index: i, value: el.toLowerCase() };
})

// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
  if (a.value > b.value) {
    return 1;
  }
  if (a.value < b.value) {
    return -1;
  }
  return 0;
});

// container for the resulting order
var result = mapped.map(function(el){
  return list[el.index];
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Last Updated: 8/12/2019, 7:24:50 PM