gpt4 book ai didi

javascript - AngularJS:使用过滤器将数组拆分为数组

转载 作者:行者123 更新时间:2023-11-29 19:13:08 25 4
gpt4 key购买 nike

有一个对象数组,我想拆分成几个数组。这些字符串在 AngularJS 中工作完美,并按照我想要的方式将整个数组 arr 分成四个数组:

    var arr0 = $filter('filter')(arr, { filterVal: 0 }, true);
var arr1 = $filter('filter')(arr, { filterVal: 10 }, true);
var arr2 = $filter('filter')(arr, { filterVal: 50 }, true);
var arr3 = $filter('filter')(arr, { filterVal: 60 }, true);

实际上,total上面的四个数组是原始数组(因为每一项中的filterVal总是等于0、10、50或60)。

那么,问题是如何让上面的代码更短呢?所以,我需要在一行中将 arr 拆分为 new_arr,这样

new_arr[0] is equal to arr0,
new_arr[1] is equal to arr1,
new_arr[2] is equal to arr2,
new_arr[3] is equal to arr3.

换句话说,我想使用一串代码(如果可能的话)而不是四串代码。 AngularJS 有可能吗?

这样我会让它更有活力(不拘泥于四个)。

谢谢。

刚刚添加:例如,

    arr = [
{"code":"kfk", "flag":"dfmk", "filterVal": 0},
{"code":"asg", "flag":"sdg3", "filterVal": 50},
{"code":"asdf", "flag":"34t", "filterVal": 10},
{"code":"hsdfh", "flag":"dfsg43", "filterVal": 50},
];

预计会被授予

var new_arr[0] = [{"code":"kfk", "flag":"dfmk", "filterVal": 0}];//0s
var new_arr[1]= [{"code":"asdf", "flag":"34t", "filterVal": 10},];//10s
var new_arr[2]= [{"code":"asg", "flag":"sdg3", "filterVal": 50},{"code":"hsdfh", "flag":"dfsg43", "filterVal": 50}];//50s
var new_arr[3]= [];//60s

最佳答案

您可以使用纯 Javascript 和数组进行分组。

var array = [{ "code": "kfk", "flag": "dfmk", "filterVal": 0 }, { "code": "asg", "flag": "sdg3", "filterVal": 50 }, { "code": "asdf", "flag": "34t", "filterVal": 10 }, { "code": "hsdfh", "flag": "dfsg43", "filterVal": 50 }, ],
groups = [{ filterVal: 0 }, { filterVal: 10 }, { filterVal: 50 }, { filterVal: 60 }],
result = groups.map(function (a) { return []; });

array.forEach(function (a) {
groups.some(function (b, i) {
var k = Object.keys(b)[0];
return a[k] === b[k] && result[i].push(a);
});
});

console.log(result);

或者你可以使用更线性的方法

var array = [{ "code": "kfk", "flag": "dfmk", "filterVal": 0 }, { "code": "asg", "flag": "sdg3", "filterVal": 50 }, { "code": "asdf", "flag": "34t", "filterVal": 10 }, { "code": "hsdfh", "flag": "dfsg43", "filterVal": 50 }, ],
filter = [{ filterVal: 0 }, { filterVal: 10 }, { filterVal: 50 }, { filterVal: 60 }],
groups = Object.create(null),
result = filter.map(function (a) { return []; });

filter.forEach(function (b, i) {
groups[b[Object.keys(b)[0]]] = i;
});
array.forEach(function (a) {
result[groups[a.filterVal]].push(a);
});

console.log(result);

关于javascript - AngularJS:使用过滤器将数组拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37322523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com