I am sorting an array of objects and having an issue keeping the empty objects in order, below will sort by SectionName
(() => {
const items = [{
ID: 20,
SectionName: "Cabinet"
},
{
ID: 0,
SectionName: ""
},
{
ID: 0,
SectionName: ""
},
{
ID: 20,
SectionName: "Cabinet"
},
{
ID: 2,
SectionName: "Frame"
},
{
ID: 0,
SectionName: ""
},
{
ID: 3,
SectionName: "Alt"
},
{
ID: 4,
SectionName: "Upper"
},
{
ID: 0,
SectionName: ""
},
{
ID: 0,
SectionName: ""
},
{
ID: 0,
SectionName: ""
},
{
ID: 5,
SectionName: "Lower"
}
];
//items.forEach((e, i) => {
// console.log(e);
//});
// sort by name
items.sort(function(a, b) {
let nameA = a.SectionName.toUpperCase();
let nameB = b.SectionName.toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
});
console.table(items);
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
but doesn't keep the empty objects in place before the sort, what I am trying to get it to sort like is
{ID: 3, SectionName: "Alt"},
{ID: 20, SectionName: "Cabinet"},
{ID: 0, SectionName: ""},
{ID: 0, SectionName: ""},
{ID: 20, SectionName: "Cabinet"},
{ID: 2, SectionName: "Frame"},
{ID: 0, SectionName: ""},
{ID: 5, SectionName: "Lower"},
{ID: 0, SectionName: ""},
{ID: 0, SectionName: ""},
{ID: 0, SectionName: ""} ,
{ID: 4, SectionName: "Upper"}
Array.prototype.sort()lets you compare two items against each other and lets you determine which one has the higher sorting order. It seems that what you're trying to achieve goes beyond checking only two objects, but rather evaluating the entire array. I don't thinkArray.prototype.sort()will be enough here. What is the logic for the requested order? It seems a bit arbitrary.