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.
CodePudding user response:
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
CodePudding user response:
So check if the age is defined. If not set it to a large number to force it to the end.
const names = [
{
name: "John",
age: 27
},{
name: "Charles",
},{
name: "Ellen",
age: 30
},{
name: "Mario",
},
{
name: "Emanuelle",
age: 18
}
]
function getAge (obj) {
return obj.age === undefined ? Number.MAX_VALUE : obj.age;
}
names.sort(function (a, b) {
// if (a.age === b.age) {
// return a.name.localeCompare(b.name);
// }
return getAge(a) - getAge(b);
})
console.log(names);
CodePudding user response:
You could check for the property and if not exist, move this objects to bottom. for the rest sort by age
.
const
names = [{ name: "John", age: 27 }, { name: "Charles" }, { name: "Ellen", age: 30 }, { name: "Mario" }, { name: "Emanuelle", age: 18 }];
names.sort((a, b) =>
('age' in b) - ('age' in a) || // sort object without `age` to bottom
a.age - b.age // sort by `age`
);
console.log(names);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
Sort not work properly because any number operation with undefined
are NaN
I.E: 1 - undefined
= NaN
.
For this sort, you can use destructuring defaults, try this:
const names = [
{
name: "John",
age: 27
},{
name: "Charles",
},{
name: "Ellen",
age: 30
},{
name: "Mario",
},
{
name: "Emanuelle",
age: 18
}
]
names.sort( ({age : agea = Number.MAX_VALUE}, {age : ageb = Number.MAX_VALUE}) => agea-ageb)
console.log(names)