问题:
This code returns an array of arrays:
var values = [[1],["a"],,["b"],[""],["c"]];
var noBlankValues = values.filter(function (el) {
var v = el != null &...
可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
This code returns an array of arrays:
var values = [[1],["a"],,["b"],[""],["c"]];
var noBlankValues = values.filter(function (el) {
var v = el != null && el != "";
return v;
});
console.log(noBlankValues);
How should I change it to get an array like [1,"a","b","c"]
? I tried this but with no luck:
var values = [[1],["a"],,["b"],[""],["c"]];
var noBlankValues = values.filter(function (el) {
var v = el != null && el != "";
return v[0];
});
console.log(noBlankValues);
回答1:
You could map array items and then filter for empty strings.
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);
回答2:
You can use flat
and filter
like this. The flat
method also removes holes in arrays (MDN)
const values = [[1],["a"],,["b"],[""],["c"]];
const noBlankValues = values.flat().filter(a => a);
console.log(noBlankValues);
The above filter removes all the falsy
values. If you specifically want to remove null and empty strings:
const values = [[1],["a"],,["b"],[""],["c"]];
const noBlankValues = values.flat().filter(a => a !== null && a !== "");
console.log(noBlankValues);
Note: Browser compatibility for flat()
回答3:
It is worth noting that, filter function requires a boolean return MSDN
This will filter the values first, giving you the array of no blanks.
values = [[1],["a"],,["b"],[""],["c"]];
noBlankValues = values.filter(function (el) {
return el[0] != null && el[0] != "";
});
console.log(noBlankValues);
You can the loop through the array using the map function to get the items directly in the main array.
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);