使用Lodash从嵌套数组中删除数组项

时间:2019-07-11 05:39:43

标签: javascript arrays lodash

如果子集数组的值为 null 或使用lodash的值为0(零),则从嵌套数组中删除数组项。我尝试使用过滤器,但是我正在寻找性能方面的最佳方法。

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"]];
console.log("arr", arr);
// output should be [["a","b","c"],["d","e","f"]]

4 个答案:

答案 0 :(得分:4)

您可以使用filter()some()

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"]];

let res = arr.filter(x => !x.some(a => a === null || a === 0))
console.log(res)

答案 1 :(得分:2)

  • 具有lodashfilterincludes函数:

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"]];
const result = _.filter(arr, x => !_.includes(x, null) && !_.includes(x, 0))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.min.js"></script>

  • 具有ES6filtersome函数:

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"]];
const result = arr.filter( x => !x.some(s => s === null || s === 0))
console.log(result)

  • 使用ES6reduce

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"]];
const result = arr.reduce( (acc, c) => {
  if(c.some(x => x === null || x === 0)) {
    return acc
  }
  return [...acc, c]
},[])

console.log(result)

答案 2 :(得分:0)

您可以尝试使用filter()some()

请注意::以下解决方案也适用于其他 falsy 输入,例如""undefined

使用Lodash

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"],["d",undefined,"f"],["d","e","f",""]];
var res = _.filter(arr, a => !a.some(i => !i));
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.core.min.js" integrity="sha256-NAQPwApfC7Ky1Y54LjXf7UrUQFbkmBEPFh/7F7Zbew4=" crossorigin="anonymous"></script>

使用Vanilla JS

const arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"],["d",undefined,"f"],["d","e","f",""]];
var res = arr.filter(a => !a.some(i => !i));
console.log(res);

答案 3 :(得分:0)

//cost will not let modify the variable
let arr = [["a","b","c"],["f","r","p",0],["r",22,null,"t"],["d","e","f"]];


arr  = arr.filter(aItem=>{
   //compact will remove null, 0 , undefined values from array item
   return aItem.length===_.compact(aItem).length;
});

console.log("...arr",arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.core.min.js"></script>