How to return element out of array using filter method?

问题: This code returns an array of arrays: var values = [[1],["a"],,["b"],[""],["c"]]; var noBlankValues = values.filter(function (el) { var v = el != null &amp...

问题:

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

  • 发表于 2019-01-16 19:17
  • 阅读 ( 192 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除