// sorted reverse alphabetically const persons = [ { name: "Richa", city: "St Louis",…
- User
// sorted reverse alphabetically const persons = [ { name: "Richa", city: "St Louis", state: "MO" }, { name: "Mike", city: "Washington", state: "MO" }, { name: "George", city: "San Jose", state: "CA" } ] print in reverse alphabetical order by name
- Assistant
// First, use the sort() method to sort the array alphabetically in descending order based on name property persons.sort((a, b) => { if(a.name < b.name) { return 1; } if(a.name > b.name) { return -1; } return 0; });
// Then, use a loop to print out the sorted array for(let i=0; i<persons.length; i++) { console.log(persons[i]); }
// Output: // {name: "Richa", city: "St Louis", state: "MO"} // {name: "Mike", city: "Washington", state: "MO"} // {name: "George", city: "San Jose", state: "CA"}
- User
do it in one line
- Assistant
Here's a one-liner solution using the chained array prototype methods sort() and forEach():
persons.sort((a, b) => b.name.localeCompare(a.name)).forEach(person => console.log(person));This code sorts the
personsarray in descending order based on thenameproperty and then uses the forEach() method to print each person to the console. ThelocaleCompare()method is used to compare the strings in reverse order.