JavaScript Sort An Array by firstName Property (Alphabetically)

To sort array by firstName property in alphabetical order, you can use the sort() method of Array in JavaScript. The sort() method will sort the elements of an array in place and return the sorted array.

sort an array by firstname property in JavaScript

Sort An Array by firstName Property (Alphabetically) In JavaScript

You can use the following script to sort array by firstName property in alphabetical order.

var arr = [];

arr.push({firstName:"John", lastName:"Doe"});

arr.push({firstName:"Jane", lastName:"Doe"});

arr.push({firstName:"Barry", lastName:"Smith"});

console.log(arr);

// Sort by firstname property in ascending order

arr.sort(function (a, b) {

return a.firstName.localeCompare(b.firstName);

});

console.log(arr);

Output:

[{

firstName: “Barry”,

lastName: “Smith”

}, {

firstName: “Jane”,

lastName: “Doe”

}, {

firstName: “John”,

lastName: “Doe”

}]

As you can see from the output, the sort() method sorts the elements of an array in place and returns the sorted array. The sort() method uses the localeCompare() method to compare two strings.

The localeCompare() method returns a negative value if the first string is less than the second string, a positive value if the first string is greater than the second string, or 0 if the strings are equal.

You can also use the following script to sort array by firstName property in alphabetical order.

var arr = [];

arr.push({firstName:"John", lastName:"Doe"});

arr.push({firstName:"Jane", lastName:"Doe"});

arr.push({firstName:"Barry", lastName:"Smith"});

console.log(arr);

// Sort by firstname property in ascending order

arr.sort(function (a, b) {

if (a.firstName < b.firstName) {

return -1;

} else if (a.firstName > b.firstName) {

return 1;

} else {

return 0;

}

});

console.log(arr);

Output:

[{

firstName: “Barry”,

lastName: “Smith”

}, {

firstName: “Jane”,

lastName: “Doe”

}, {

firstName: “John”,

lastName: “Doe”

}]

As you can see from the output, the sort() method sorts the elements of an array in place and returns the sorted array.

The sort() method uses the compare function to compare two strings. The compare function takes two parameters, a and b, and returns a negative value if the first string is less than the second string, a positive value if the first string is greater than the second string, or 0 if the strings are equal.

Conclusion

In this article, you’ve learned how to sort an array by firstName property in alphabetical order in Javascript. You can use the sort() method of Array in JavaScript to sort array by firstName property in alphabetical order.

The sort() method will sort the elements of an array in place and return the sorted array. Thanks for reading!

Leave a Reply