I'm trying to sort 2 objects based on value.first_name. One ascending alphabetical order. The other descending alphabetical order. However, they are both sorting decending. What am I doing wrong? The goal is to arrange the objects in this array based on the value of first_name.
var participants = [
{
id: "992543",
first_name: "",
last_name: "",
company: null,
notes: "",
registrationType: "",
alerts: [ ],
reg_scan: null
},
{
id: "999070",
first_name: "Tori",
last_name: "Fullard",
company: null,
notes: "",
registrationType: "Staff",
alerts: [ ],
reg_scan: null
},
{
id: "99265",
first_name: "Ronald",
last_name: "Brown",
company: null,
notes: "",
registrationType: "Dean's Guest",
alerts: [ ],
reg_scan: null
},
{
id: "992279",
first_name: "Laila",
last_name: "Shetty",
company: null,
notes: "",
registrationType: "Table Guest",
alerts: [
{
alert_id: "1",
dismissed: "0"
}
],
reg_scan: null
},
{
id: "992248",
first_name: "Paul",
last_name: "Keenan",
company: null,
notes: "",
registrationType: "Table Guest",
alerts: [ ],
reg_scan: null
}
];
var az_part = participants;
var za_part = participants;
az_part.sort(function(a, b) {
var nameA = a.first_name.toLowerCase();
var nameB = b.first_name.toLowerCase();
if (nameA > nameB) return 1;
if (nameA < nameB) return -1;
return 0;
});
za_part.sort(function(a, b) {
var nameA = a.first_name.toLowerCase();
var nameB = b.first_name.toLowerCase();
if (nameA > nameB) return -1;
if (nameA < nameB) return 1;
return 0;
});
az_partandza_partare the SAME thing,participants. There is only one array, so you're sorting that same array twice. Checkparticipantsand you'll see that it's also sorted the same way even though your code doesn't explicitly sort it. You need to copy the array (participants.slice(0)will do it - you don't particularly need a deep-copy here)