I know that undefined values should be sent to the end of the result, but what about non-existent keys? (Shouldn’t be the same?) It seems sort doesn’t work in those cases:
const names = [
{
name: "John",
age: 27
},{
name: "Charles",
},{
name: "Ellen",
age: 30
},{
name: "Mario",
},
{
name: "Emanuelle",
age: 18
}
]
names.sort(function (a, b) {
if (a.age > b.age) return 1;
if (a.age < b.age) return -1;
return 0;
})
console.log(names) // Sort not working, prints original order
Ideally I want to modify the "names" array and not create/reassign more variables.
>Solution :
Your default sort solution is set to keep the item in its current position –> return 0. You could provide another conditional that captures undefined and return -1
const
names = [{ name: "John", age: 27 }, { name: "Charles" }, { name: "Ellen", age: 30 }, { name: "Mario" }, { name: "Emanuelle", age: 18 }];
names.sort(function (a, b) {
if(b.age === undefined) return -1;
if (a.age > b.age) return 1;
if (a.age < b.age) return -1;
return 0;
})
console.log(names) // Sort not working, prints original order