我正在使用这种结构:
[
[
{
"comments":"asd",
"movement":"Back Squat",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"330"
}
],
[
{
"comments":"asd",
"movement":"Bench Press",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"100"
}
],
[
{
"comments":"Comment",
"movement":"Clean",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"195"
}
],
[
],
[
],
[
{
"comments":"Front squat comment alpha",
"movement":"Front Squat",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"315"
}
],
[
],
[
],
[
],
[
],
[
],
[
{
"comments":"abc",
"movement":"Strict Press",
"userID":"wDHZv3OL55SIymHkhMUejNleNkx1",
"weight":"155"
}
]
]
这是我在JSON格式中使用的输入。如您所见,有多个空数组。
我如何过滤这些数组并删除空数组?
答案 0 :(得分:7)
使用原生Array#filter
或lodash' _.filter()
,并保持子数组的长度不是0。
<强> Array#filter
强>
var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]];
var result = arrs.filter(function(sub) {
return sub.length;
});
console.log(result);
&#13;
Lodash&#39; _.filter()
与_.size
:
var arrs = [[{"comments":"asd","movement":"Back Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"330"}],[{"comments":"asd","movement":"Bench Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"100"}],[{"comments":"Comment","movement":"Clean","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"195"}],[],[],[{"comments":"Front squat comment alpha","movement":"Front Squat","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"315"}],[],[],[],[],[],[{"comments":"abc","movement":"Strict Press","userID":"wDHZv3OL55SIymHkhMUejNleNkx1","weight":"155"}]];
var result = _.filter(arrs, _.size);
console.log(result);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
答案 1 :(得分:5)
如果顶级数组中的所有项都是数组,那么您可以使用reject谓词来保存isEmpty。
let result = _.reject(data, _.isEmpty);
isEmpty也会为空对象返回true,所以如果你的顶级数组可以包含这些项,那么只需删除空数组就可以组成一个新函数来返回空数组并将其用作谓词拒绝:
let isEmptyArray = item => _.isArray(item) && _.isEmpty(item);
let result = _.reject(data, isEmptyArray);
答案 2 :(得分:0)
依次测试每个数组以查看它是否具有非零(真实)长度。如果是,请将其放入新阵列中。
var array_of_arrays = [[1], [1,1], [], [], [1]];
var array_of_non_empty_arrays = array_of_arrays.filter((array) => array.length);
console.log(array_of_non_empty_arrays);