Given array need to sort by firstname using JavaScript.
var user = [{
bio: null,
email: "[email protected]",
firstname: "Job",
id: 101,
lastname: "Johnson",
},
{
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 102,
lastname: "Williams",
},
{
bio: null,
email: "[email protected]",
firstname: "Davis",
id: 103,
lastname: "Jones",
}];
Sort Alphabetically JavaScript Example code:
Use user.sort and pass a function that takes two arguments and compares them (comparator).
How’s work:-
- Something negative if the first argument is less than second (should be placed before the second in resulting array)
- something positive if the first argument is greater (should be placed after the second one)
- 0 if those two elements are equal.
Source: https://stackoverflow.com/
<!DOCTYPE html>
<html>
<body>
<script>
var user = [{
bio: null,
email: "[email protected]",
firstname: "Job",
id: 101,
lastname: "Johnson",
},
{
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 102,
lastname: "Williams",
},
{
bio: null,
email: "[email protected]",
firstname: "Davis",
id: 103,
lastname: "Jones",
}];
user.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
console.log(user);
</script>
</body>
</html>
Output:
Shortest possible code with ES6!
<script>
var user = [{
bio: null,
email: "[email protected]",
firstname: "Job",
id: 101,
lastname: "Johnson",
},
{
bio: null,
email: "[email protected]",
firstname: "Anna",
id: 102,
lastname: "Williams",
},
{
bio: null,
email: "[email protected]",
firstname: "Davis",
id: 103,
lastname: "Jones",
}];
user.sort((a, b) => a.firstname.localeCompare(b.firstname))
console.log(user);
</script>
Do comment if you have doubts and suggestion on this tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version