如何使用过滤方法从数组中提取 return 个元素?

How to return element out of array using filter method?

这段代码returns一个数组的数组:

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);

您可以映射数组项,然后过滤空字符串。

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);

您可以使用 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);

上面的过滤器删除了所有 falsy 值。如果您特别想删除 null 和空字符串:

const values = [[1],["a"],,["b"],[""],["c"]];
const noBlankValues = values.flat().filter(a => a !== null && a !== "");
console.log(noBlankValues);

注意:flat() 的浏览器兼容性

值得注意的是,过滤函数需要一个布尔值return 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);