EN
JavaScript - sort array of objects by string property value
0 points
In this article, we would like to show you how to sort array of objects by string property value using JavaScript.
Quick solution:
xxxxxxxxxx
1
array.sort(function(a, b) {
2
if ( a.name < b.name ){
3
return -1;
4
}
5
if ( a.name > b.name ){
6
return 1;
7
}
8
return 0;
9
});
In this example, we sort an array of objects by name
property value using the custom compare function as an argument of the sort()
method.
xxxxxxxxxx
1
var array = [
2
{ name: 'Mark', age: 25 },
3
{ name: 'Ann', age: 32 },
4
{ name: 'Chris', age: 19 }
5
];
6
7
array.sort(function(a, b) {
8
if ( a.name < b.name ){
9
return -1;
10
}
11
if ( a.name > b.name ){
12
return 1;
13
}
14
return 0;
15
});
16
17
console.log(JSON.stringify(array, null, 4));