js对象数组深度去重和深度排序
使⽤collect.js处理数组和对象
引⼊collect.js
npm install collect.js --save
或
<script src="cdn.jsdelivr/npm/collect.js@4.0.25/build/collect.min.js"></script>
深度去重
简单数组去重
const collection = collect([1, 1, 1, 2, 3, 3]);
const unique = collection.unique();
unique.all();
//=> [1, 2, 3]
对象数组去重
const collection = collect([
{ name: 'iPhone 6', brand: 'Apple', type: 'phone' },
{ name: 'iPhone 5', brand: 'Apple', type: 'phone' },
{ name: 'Apple Watch', brand: 'Apple', type: 'watch' },
{ name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
{ name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' },
]);
const unique = collection.unique('brand');
unique.all();
//=> [
//=> { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
//=> { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
//=> ]
对象数组回调函数处理去重
const collection = collect([
{ name: 'iPhone 6', brand: 'Apple', type: 'phone' },
{ name: 'iPhone 5', brand: 'Apple', type: 'phone' },
{ name: 'Apple Watch', brand: 'Apple', type: 'watch' },
{ name: 'Galaxy S6', brand: 'Samsung', type: 'phone' },
{ name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' }, ]);
const unique = collection.unique(function (item) {
return item.brand pe;
});
unique.all();
//=> [
//=> { name: 'iPhone 6', brand: 'Apple', type: 'phone' },
//=> { name: 'Apple Watch', brand: 'Apple', type: 'watch' },
//=> { name: 'Galaxy S6', brand: 'Samsung', type: 'phone' }, //=> { name: 'Galaxy Gear', brand: 'Samsung', type: 'watch' }, //=> ]
简单排序和深度排序
简单数组排序
const collection = collect([5, 3, 1, 2, 4]);
const sorted = collection.sort();
sorted.all();
//=> [1, 2, 3, 4, 5]
简单数组回调函数处理排序
const collection = collect([5, 3, 1, 2, 4]);
const sorted = collection.sort(function (a, b) {
return b - a;
});
sorted.all();
/
/=> [5, 4, 3, 2, 1]
sort函数 js对象数组排序
const collection = collect([
{ name: 'Desk', price: 200 },
{ name: 'Chair', price: 100 },
{ name: 'Bookcase', price: 150 },
]);
const sorted = collection.sortBy('price');
sorted.all();
//=> [
//=> { name: 'Chair', price: 100 },
/
/=> { name: 'Bookcase', price: 150 },
//=> { name: 'Desk', price: 200 },
//=> ]
对象数组回调函数处理排序
const collection = collect([
{ name: 'Desk', colors: ['Black', 'Mahogany'] },
{ name: 'Chair', colors: ['Black'] },
{ name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
]);
const sorted = collection.sortBy(function (product, key) {
return product['colors'].length;
});
sorted.all();
//=> [
//=> { name: 'Chair', colors: ['Black'] },
//=> { name: 'Desk', colors: ['Black', 'Mahogany'] },
//=> { name: 'Bookcase', colors: ['Red', 'Beige', 'Brown'] },
//=> ]
降序排序
使⽤⽅法和sortBy⼀样,但得到降序结果
============================================== ==============================================
【猿2048】www.mk2048
更多专业前端知识,请上 【猿2048】www.mk2048
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论