sort object after name key alphabetically in javascript

You can use the sort() method of the Array object to sort an array of objects based on the values of a specific key, in this case the "name" key. Here's an example of how to sort the objects alphabetically by name:

index.tsx
// An array of objects to be sorted
let arr = [
    { name: "John", age: 25 },
    { name: "Mary", age: 30 },
    { name: "Peter", age: 20 }
];

// Sort the objects by name
arr.sort((a, b) => {
    let nameA = a.name.toUpperCase(); // ignore upper and lowercase
    let nameB = b.name.toUpperCase(); // ignore upper and lowercase
    if (nameA < nameB) {
        return -1;
    }
    if (nameA > nameB) {
        return 1;
    }
  
    // names must be equal
    return 0;
});

// Output the sorted objects
console.log(arr); 
526 chars
25 lines

In this example, arr is an array of objects with a "name" key and an "age" key. We use the sort() method to sort the array according to the values of the "name" key. Inside the sort() method, we compare the values of the "name" key using toUpperCase() method, which makes sure that the comparison is case-insensitive. Finally, we return a negative, zero, or positive value depending on whether the first name is less than, equal to, or greater than the second name.

gistlibby LogSnag