假设我们有以下对象数组-
const people = [{ firstName: 'Ram', id: 301 }, { firstName: 'Shyam', lastName: 'Singh', id: 1016 }, { firstName: 'Dinesh', lastName: 'Lamba', id: 231 }, { id: 341 }, { firstName: 'Karan', lastName: 'Malhotra', id: 441 }, { id: 8881 }, { firstName: 'Vivek', id: 301 }];
我们需要对该数组进行排序,以便首先显示具有firstName和lastName属性的对象,然后显示具有firstName或lastName的对象,最后显示既没有firstName也没有lastName的对象。
因此,此代码将是-
const people = [{ firstName: 'Ram', id: 301 }, { firstName: 'Shyam', lastName: 'Singh', id: 1016 }, { firstName: 'Dinesh', lastName: 'Lamba', id: 231 }, { id: 341 }, { firstName: 'Karan', lastName: 'Malhotra', id: 441 }, { id: 8881 }, { firstName: 'Vivek', id: 301 }]; const sorter = (a, b) => { if(a.firstName && a.lastName){ return -1; }else if(b.firstName || b.lastName){ return 1; }else{ return -1; }; }; people.sort(sorter); console.log(people);
输出结果
控制台中的输出将为-
[ { firstName: 'Karan', lastName: 'Malhotra', id: 441 }, { firstName: 'Dinesh', lastName: 'Lamba', id: 231 }, { firstName: 'Shyam', lastName: 'Singh', id: 1016 }, { firstName: 'Ram', id: 301 }, { firstName: 'Vivek', id: 301 }, { id: 8881 }, { id: 341 } ]