我在javascript中有一个数组数组。并希望执行某种计算。
我的数组如下图所示:
哪里:
-第一个值是一个代码。
-第二个值是一个大小。
-每个数组的第三个值是一个计数。
我想做的是找到所有计数均为0的所有组。
例如:
我试过的
var a = [];
$.each(arr[21].splits, function(idx, val) {
console.log(val);
var current_code = arr[21].splits[idx][0];
a[current_code] = [];
a[current_code].push(arr[21].splits[idx]);
});
但是找不到正确的解决方案..谢谢!
数据集:
{"code":"sjm","splits":[["FOG","L","0"],["FOG","XL","-1"],["FOG","XXXL","2"],["FOG","S","7"],["FOG","M","0"],["FOG","XXL","6"],["BLK","LT","30"],["BLK","XLT","23"],["BLK","XXXLT","0"],["BLK","L","102"],["BLK","XL","302"],["BLK","XXXL","64"],["BLK","S","25"],["BLK","XXLT","0"],["BLK","M","485"],["BLK","XXL","159"],["BGE","L","106"],["BGE","XL","41"],["BGE","XXXL","15"],["BGE","S","4"],["BGE","M","39"],["BGE","XXL","0"],["RED","L","36"],["RED","XL","41"],["RED","XXXL","8"],["RED","S","5"],["RED","M","19"],["RED","XXL","2"],["NVY","L","0"],["NVY","XL","0"],["NVY","XXXL","0"],["NVY","S","28"],["NVY","M","0"],["NVY","XXL","0"]]}
P.S在上面的屏幕上-没有颜色代码,组中的所有值均为0。
因此,没有任何输出。
最佳答案
我猜(因为您谈论分组),您将先reduce
然后再filter
您可以减少以使数组按第一个索引分组,您可以像这样进行处理
function groupBy( arr, t ) {
return arr.reduce( (agg, c) => {
const key = t(c);
if (!agg[key]) {
agg[key] = [];
}
agg[key].push( c );
return agg;
}, {} );
}
然后您可以将其用作
const result = groupBy( arr[21], item => item[0] );
给你一个像
{ "NVY": [["NVY", "S", "28"], ...] }
然后您可以找到总共
0
“count”的那些function find( obj, predicate ) {
return Object.keys( obj ).filter( key => predicate( obj[key] ) );
}
然后您可以使用像
const groups = find( result, items => !items.some( i => i[2] !== "0" ) );
给您结果(以防NVY没有任何不为“0”的项目)
["NVY", "..."]
然后可以将其与
code
属性结合使用因此,如果将所有这些结合起来,将会得到类似
const set = {"code":"sjm","splits":[["FOG","L","0"],["FOG","XL","-1"],["FOG","XXXL","2"],["FOG","S","7"],["FOG","M","0"],["FOG","XXL","6"],["BLK","LT","30"],["BLK","XLT","23"],["BLK","XXXLT","0"],["BLK","L","102"],["BLK","XL","302"],["BLK","XXXL","64"],["BLK","S","25"],["BLK","XXLT","0"],["BLK","M","485"],["BLK","XXL","159"],["BGE","L","106"],["BGE","XL","41"],["BGE","XXXL","15"],["BGE","S","4"],["BGE","M","39"],["BGE","XXL","0"],["RED","L","36"],["RED","XL","41"],["RED","XXXL","8"],["RED","S","5"],["RED","M","19"],["RED","XXL","2"],["NVY","L","0"],["NVY","XL","0"],["NVY","XXXL","0"],["NVY","S","28"],["NVY","M","0"],["NVY","XXL","0"]]};
function groupBy( arr, t ) {
return arr.reduce( (agg, c) => {
const key = t(c);
if (!agg[key]) {
agg[key] = [];
}
agg[key].push( c );
return agg;
}, {} );
}
function find( obj, predicate ) {
return Object.keys( obj ).filter( key => predicate( obj[key] ) );
}
const result = groupBy( set.splits, item => item[0] );
const groups = find( result, items => !items.some( i => i[2] !== "0" ) );
console.log( groups );
// and combined
console.log( groups.map( g => `${set.code}-${g}` ) );
// for verification
console.log( result );