4

Looking to remove an array item from the nested array if subset array have value a null or 0(zero) using lodash. I tried filter but I am looking for best way in term of performance.

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 Answers 4

3

You can use filter() and 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)

Sign up to request clarification or add additional context in comments.

Comments

2
  • With lodash : filter and includes functions:

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>

  • With ES6 : filter and some functions:

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)

  • With ES6 : reduce:

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)

Comments

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>

Comments

0

You can try with filter() and some().

Please Note: The following solution will also work for other falsy inputs like "" and undefined.

Using 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>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.