I am sorting an array contains objects. I am sorting the last name based on alphabetical order. But when I print out, only the first item of the sorted array appear and it filled the array. What is mean is array =[{name: "White, David", score:100},{name: "Bee, Axis", score:101}] after sorting by last name the array becomes array =[{name: "Bee, Axis", score:101},{name: "Bee, Axis", score:101}], all the information are the same. I don't know what was wrong?
here is to populate the array:
for (let i = 0; i < 10; i++)
{
record.Customer= customerName[i];
record.MonthlyCharge = monthlyCharge[i];
record.PastDueAmount = pastDueAmount[i];
record.DaysPastDue = numDaysPastDue[i];
records.push(record);
table += `<tr>`;
table +=`<td>${record.Customer}</td>`;
table +=`<td>$${record.MonthlyCharge}</td>`;
table +=`<td>$${record.PastDueAmount}</td>`;
table +=`<td>${record.DaysPastDue}</td>`;
table +=`</tr>`;
}
tableBody.innerHTML = table;
To sort the array
nameColumn.addEventListener("click", function (){
records.sort((a,b)=>a.Customer.localeCompare(b.Customer));
updateTable();
});
function updateTable()
{
let table = "";
for (let record of records)
{
table += `<tr>`;
table +=`<td>${record.Customer}</td>`;
table +=`<td>$${record.MonthlyCharge}</td>`;
table +=`<td>$${record.PastDueAmount}</td>`;
table +=`<td>${record.DaysPastDue}</td>`;
table +=`</tr>`;
}
tableBody.innerHTML = table;
}
customerName,monthlyCharge,pastDueAmount, andnumDaysPastDueseparate arrays and you have to build an array of objects every time? Or do you already have an array of objects?