此代码返回一个数组数组:
var values = [[1],["a"],,["b"],[""],["c"]];
var noBlankValues = values.filter(function (el) {
var v = el != null && el != "";
return v;
});
console.log(noBlankValues);
如何更改它以获得类似[1,"a","b","c"]
的数组?
我尝试了这个,但是没有运气:
var values = [[1],["a"],,["b"],[""],["c"]];
var noBlankValues = values.filter(function (el) {
var v = el != null && el != "";
return v[0];
});
console.log(noBlankValues);
答案 0 :(得分:2)
您可以映射数组项,然后过滤空字符串。
var values = [[1], ["a"], , ["b"], [""], ["c"]],
result = values
.map(([v]) => v)
.filter(v => v !== '');
console.log(result);
ES5
var values = [[1], ["a"], , ["b"], [""], ["c"]],
result = values
.map(function (v) { return v[0]; })
.filter(function (v) { return v !== ''; });
console.log(result);
答案 1 :(得分:1)
您可以像这样使用flat
和git log
。 filter
方法还可以删除数组(MDN)中的孔
flat
上面的过滤器删除了所有falsy
值。如果您特别想删除空字符串:
const values = [[1],["a"],,["b"],[""],["c"]];
const noBlankValues = values.flat().filter(a => a);
console.log(noBlankValues);
答案 2 :(得分:1)
值得注意的是,过滤器功能需要布尔返回MSDN
这将首先过滤值,为您提供无空格的数组。
values = [[1],["a"],,["b"],[""],["c"]];
noBlankValues = values.filter(function (el) {
return el[0] != null && el[0] != "";
});
console.log(noBlankValues);
您可以使用map函数在数组中循环,以直接在主数组中获取项目。
values = [[1],["a"],,["b"],[""],["c"]];
noBlankValues = values.filter(function (el) {
return el[0] != null && el[0] != "";
}).map(function(item) {
return item[0];
});
console.log(noBlankValues);