[英]Remove undefined from multidimensional array
So I need to remove empty (undefined) items from the multidimensional array. 因此,我需要从多维数组中删除空的(未定义)项目。 Atm my code looks like this (it's a method I run so that's why i am using this
: Atm我的代码看起来像这样(这是我运行的一种方法,所以这就是我使用this
的原因:
f: function(arr) {
var __ = this;
arr = arr.filter(function(item) {
return Array.isArray(item) ? __.f(item) : typeof(item) !== "undefined";
});
return arr;
}
but if i run console.log(myObject.f([1, 2, , , , , 3, 4, [5, , , , , ], 6, , , , 8, 3, [[[], 9]]]));
但是如果我运行console.log(myObject.f([1, 2, , , , , 3, 4, [5, , , , , ], 6, , , , 8, 3, [[[], 9]]]));
i get [ 1, 2, 3, 4, [ 5, , , , ], 6, 8, 3, [ [ [], 9 ] ] ]
and that is kinda weird result. 我得到[ 1, 2, 3, 4, [ 5, , , , ], 6, 8, 3, [ [ [], 9 ] ] ]
,,,, [ 1, 2, 3, 4, [ 5, , , , ], 6, 8, 3, [ [ [], 9 ] ] ]
,6,8,3 [ 1, 2, 3, 4, [ 5, , , , ], 6, 8, 3, [ [ [], 9 ] ] ]
,这有点奇怪。 I goes pretty well for the first layer but removes only one undefined from inner layers. 对于第一层,我做得很好,但是从内部层中只删除了一个未定义的层。 Also I would like to remove a subarray that consists of no items. 我也想删除一个不包含任何项目的子数组。
How about something like this: 这样的事情怎么样:
var arr = [1, 2, , , , , 3, 4, [5, , , , , ], 6, , , , 8, 3, [[[], 9]]];
var remove = function (array) {
var result = [];
array.forEach(function (item) {
if (Array.isArray(item) && item.length!=0) {
// Item is a nested array, go one level deeper recursively
result.push(remove(item));
}
else if (typeof item !== 'undefined') {
result.push(item);
}
});
return result;
};
And then console.log(remove(arr));
然后console.log(remove(arr));
gives us [1, 2, 3, 4, [5], 6, 8, 3, [[[], 9]]]
给我们[1, 2, 3, 4, [5], 6, 8, 3, [[[], 9]]]
Use reductions people! 用减人! They are beautiful! 他们好美!
function stripUndefined (arr) {
return arr.reduce(function (result, item) {
result.push( Array.isArray(item) && !item.length ? stripUndefined(item) : item );
return result;
}, []);
}
Similar to Gilad's answer, but completely skipping arrays that result in an empty array (eg [,,,,,]
) 与Gilad的答案类似,但是完全跳过了导致空数组的数组(例如[,,,,,]
)
function cleanArray2d(array){
var result = [];
array.forEach(function (item) {
if (Array.isArray(item) && item.length!=0) {
// Item is a nested array, go one level deeper recursively
var nestedArray = cleanArray2d(item);
if (nestedArray.length > 0)
result.push(cleanArray2d(item));
}
else if (typeof item !== 'undefined' && item != "") {
result.push(item);
}
});
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.