javascript-sort

JavaScript Sort

Notes

  • Javascript’s sort function is basically sorted by string(even if the value is a number).
    1
    var arr = [2,12,3,4,1];
    2
    console.log(arr.sort());
    3
    // [1, 12, 2, 3, 4]
  • Target Array is sorted in place, and return value is target Array.
    1
    var arr = [4,5,1,3,2];
    2
    arr.sort();
    3
    console.log(arr);
    4
    // [1, 2, 3, 4, 5]

    String Sort

1
var arr = ["a", "c", "b"];
2
//ASC 오름차순
3
arr.sort();
4
arr.sort(function (a, b) { 
5
    return a < b ? -1 : a > b ? 1 : 0; 
6
});
7
8
//DESC 내림차순
9
arr.sort().reverse();
10
arr.sort(function (a, b) {
11
    return a > b ? -1 : a < b : 1 : 0;
12
});

Number Sort

1
var arr = [2,1,4,5,3]
2
//ASC
3
arr.sort(function (a, b) {
4
    return a - b;
5
});
6
//DESC
7
arr.sort(function (a, b) {
8
    return b - a;
9
});

JavaScript’s Date object

1
var arr = [
2
    new Date("2018-02-02"),
3
    new Date("2018-01-11"),
4
    new Date("2018-04-11"),
5
    new Date("2018-05-30"),
6
    new Date("2018-01-23"),
7
];
8
// ASC
9
arr.sort(function (a, b) {
10
    return a - b;
11
});
12
// DESC
13
arr.sort(function (a, b) {
14
    return b - a;
15
});

Sort by multiple value

1
var arr = [
2
    {str: "a", num: "3"},
3
    {str: "b", num: "2"},
4
    {str: "a", num: "1"},
5
    {str: "a", num: "2"},
6
    {str: "b", num: "1"},
7
    {str: "a", num: "3"}
8
];
9
10
arr.sort(function (a, b) {
11
    //'str' parameter sotred by asc
12
    var b1 = a.str < b.str ? -1 : a.str > b.str ? 1 : 0;
13
    //'num' parameter sotred by desc
14
    var b2 = b.num - a.num
15
    //'b1' option is sorted first.
16
    return b1 || b2;
17
});
18
19
console.log(arr);
20
// [ { str: 'a', num: '3' },
21
//   { str: 'a', num: '3' },
22
//   { str: 'a', num: '2' },
23
//   { str: 'a', num: '1' },
24
//   { str: 'b', num: '2' },
25
//   { str: 'b', num: '1' } ]
Share