Ordering the Javascript Array

Javascript, 2016-05-30 06:53:19 UTC

1. Ordering an array;

var arrA = [10,2,4,5,0,3,4];
arrA.sort(); // [0, 10, 2, 3, 4, 4, 5]

 

2. Ordering a simple array with a function;

var arrA = [10,2,4,5,0,3,4];
// 1
arrA.sort(function(a, b){
    return a - b;
});
// 1 result
// [0, 2, 3, 4, 4, 5, 10]
 
// 2
arrA.sort(function(a, b){
    return b - b;
});
// 2 result
// [10, 5, 4, 4, 3, 2, 0]

 

3. Ordering an array object;

var anu = [{ id: 5, name: "Bolang" }, { id: 8, name: "Zorro" }, { id: 2, name: "Udin" }];
anu.sort(function(a, b){
    return b.id - a.id;
});
// result
// [{ id: 8, name: "Zorro" }, { id: 5, name: "Bolang" }, { id: 2, name: "Udin" }]

 

 

 

 


Share: