.sortBy and .orderBy
Sorts an array of object based on an object key provided by a parameter (note this is more limited than Underscore/Lodash).
- const fruits = [
- {name:"banana", amount: 2},
- {name:"apple", amount: 4},
- {name:"pineapple", amount: 2},
- {name:"mango", amount: 1}
- ];
- // Underscore
- _.sortBy(fruits, 'name');
- // => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]
- // Lodash
- _.orderBy(fruits, ['name'],['asc']);
- // => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]
- // Native
- const sortBy = (key) => {
- return (a, b) => (a[key] > b[key]) ? 1 : ((b[key] > a[key]) ? -1 : 0);
- };
- // The native sort modifies the array in place. `_.orderBy` and `_.sortBy` do not, so we use `.concat()` to
- // copy the array, then sort.
- fruits.concat().sort(sortBy("name"));
- // => [{name:"apple", amount: 4}, {name:"banana", amount: 2}, {name:"mango", amount: 1}, {name:"pineapple", amount: 2}]
Browser Support for Array.prototype.concat() and Array.prototype.sort()
1.0 ✔ | ✔ | 1.0 ✔ | 5.5 ✔ | ✔ | ✔ |
当前内容版权归 you-dont-need 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 you-dont-need .