Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

// sorted reverse alphabetically const persons = [ { name: "Richa", city: "St Louis",…

  1. 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

  2. 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"}

  3. User

    do it in one line

  4. 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 persons array in descending order based on the name property and then uses the forEach() method to print each person to the console. The localeCompare() method is used to compare the strings in reverse order.