简体   繁体   中英

Remove empty elements from an array in JavaScript Reactjs

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

remove the null array from arraylist

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

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

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

More simple and concise solution:

let newArray = array.filter(Boolean);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM