在 JavaScript 中按对象中字段的存在对数组进行排序
假设我们有以下对象数组 −
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 } ]
广告