array = [{"id":1, "name":"aabc"},{"id":2, "name":"Dog"},{"id":3, "name":"James"},{"id":4,"name":"A1"},{"id":5, "name":"112"}{"id":6, "name":"Arjun"},{"id":7, "name":"ball"}, {"id":8, "name":"john"}]
I tried this one.
array.sort((a,b) => a.name.toLocaleLowerCase().localCompare(b.name.toLocaleLowerCase());
but it is not showing the expected output
expected output = [{"id":1, "name":"112"},{"id":2, "name":"A1"},{"id":3, "name":"Arjun"},{"id":4, "name":"Dog"},{"id":5, "name":"James"},{"id":6, "name":"aabc"},{"id":7, "name":"ball"},{"id":8,"name":"john"}]
Kindly help me.
CodePudding user response:
Just sort using a comparing function that compares the strings.
var array = [{"id":1, "name":"aabc"},{"id":2, "name":"Dog"},{"id":3, "name":"James"},{"id":4,"name":"A1"},{"id":5, "name":"112"},{"id":6, "name":"Arjun"},{"id":7, "name":"ball"}, {"id":8, "name":"john"}]
var result = array.sort(function(a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
return 0
})
console.log(result);
CodePudding user response:
You can achieve this by using Array.sort()
method along with a comparison function.
Live Demo :
const arr = [{"id":1, "name":"aabc"}, {"id":2, "name":"Dog"}, {"id":3, "name":"James"}, {"id":4, "name":"A1"}, {"id":5, "name":"112"}, {"id":6, "name":"Arjun"}, {"id":7, "name":"ball"}, {"id":8, "name":"john"}];
arr.sort((a, b) => a.name > b.name ? 1 : -1);
console.log(arr);