简体   繁体   中英

Sort() with non-existent values

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.

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);

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

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; }

Sort not work properly because any number operation with undefined are NaN IE: 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM