I have an array called lunchbox
which contains items with ids. Two of these items have the same ID. What I want to do is first sort my array based on ID. Then, if the IDs are the same, then sort alphabetically.
My code returns Tuna
, Bread
, and Apple
in that order. What I want is for it to return Bread
, Tuna
, Apple
, in that order. Not sure how to proceed.
var lunchbox = [
{ id: 0, name: "Tuna" },
{ id: 1, name: "Apple" },
{ id: 0, name: "Bread" }
]
lunchbox.sort(function(a, b){
return a.id > b.id;
if (a.id === b.id){
return a.name > b.name;
}
else { return a.id > b.id; }
});
for (i = 0; i < lunchbox.length; i++){
document.getElementById("list").innerHTML += "<p>"+lunchbox[i].name+"</p>";
}
<div id="list"></div>