Home > Software engineering >  Remove empty elements from an array in JavaScript Reactjs
Remove empty elements from an array in JavaScript Reactjs

Time:02-16

[ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ]

remove the null array from arraylist

CodePudding user response:

arr = [ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ]
arr = arr.filter(elem => elem != null)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

CodePudding user response:

For example, if you want to remove null or undefined values:

var array = [ { "stockId":2,"vendorId":1,"vendorCode":"Aya - 01","price":2100 }, null, null ];
var filtered = array.filter(function (el) {
    return el != null;
});
  
console.log(filtered);

CodePudding user response:

If you want to remove false values, do something like this


var array = [
   { stockId: 2, vendo`enter code here`rId: 1, vendorCode: 'Aya - 01', price: 2100 },
   null,
   null,
];
newArray = array.filter(item => !!item);

CodePudding user response:

More simple and concise solution:

let newArray = array.filter(Boolean);

just pass javascript Boolean (builtin) function inside filter as callback function.

  • Related