Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an array item from Nested array using Lodash

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"]]
like image 233
June Avatar asked Sep 06 '25 16:09

June


2 Answers

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)
like image 96
Maheer Ali Avatar answered Sep 08 '25 14:09

Maheer Ali


  • 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)
like image 43
tolotra Avatar answered Sep 08 '25 12:09

tolotra