1、将一个数组中的值从另一个包含这些值的数组中去掉
var arr1 = [{ name: 'jk' }, { name: 'kjd' }, { name: 'ksj' }, { name: 'jh' }, { name: 'jjd' }, { name: 'js' }];
var arr2 = [{ name: 'jk' }, { name: 'js' }];
// 数组arr2中的对象完全包含在数组arr1中,那么怎么从arr1中将它们剔除呢?
var obj1 = arr1.reduce(function (res, next) {
return $.extend(res, { [next.name]: next });
}, {}); // 转成对象
for(item of arr2) {
delete obj1[item.name]; // 从对象中删除属性
}
var arr3 = Object.keys(obj1).map(function(key) {
return obj1[key];
}); // 再转回数组
image
image
image
2、分类对象
var objArr = [
{ name: 'wxm', fl: 'a' },
{ name: 'df', fl: 'c' },
{ name: 'vff', fl: 'd' },
{ name: 'edd', fl: 'b' },
{ name: 'wxm', fl: 'f' },
{ name: 'dss', fl: 'd' },
{ name: 'vd', fl: 'c' },
{ name: 'vfd', fl: 'a' },
{ name: 'hg', fl: 'd' },
{ name: 'wer', fl: 'e' },
{ name: 'wxm', fl: 'a' },
{ name: 'wdd', fl: 'f' },
{ name: 'wd', fl: 'g' },
{ name: 'hjg', fl: 'e' }];
var group = [
{ gr: ['a', 'c'] },
{ gr: ['b', 'f'] },
{ gr: ['d', 'g'] },
{ gr: ['e'] }];
要将objArr中的对象按照fl属性分成group中4组
var sort = group.map(function(item) {
var gr = objArr.filter(function(perObj) {
return item.gr.includes(perObj.fl);
});
return gr;
})
console.log(sort);
image
image
网友评论