Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Remove from array if empty

I have an array looking like this:

var testArray = [
    {"cid": "1234567"},
    {"cid": "892345"},
    {"cid": ""},
    {"cid": "8267783"},
    {},
    {"cid": "096873"},
];

How do I remove, either before a for loop or when looping, where cid = "" and where is empty {}

I tried this:

for(var i = 0; testArray.length; i++){

    if(testArray.cid && testArray.cid != ""){

    }

}

This didn't work :-/ Got this error: Cannot read property "cid" from undefined

Hope this makes sense and thanks in advance :-)

like image 441
Mansa Avatar asked Jun 01 '26 17:06

Mansa


2 Answers

Use filter() to filter out undesired data.

var testArray = [
    {"cid": "1234567"},
    {"cid": "892345"},
    {"cid": ""},
    {"cid": "8267783"},
    {},
    {"cid": "096873"},
];
console.log(testArray.filter(arr => arr.cid))
like image 169
holydragon Avatar answered Jun 03 '26 06:06

holydragon


If you need to remove ALL empty values ("", null, undefined and 0):

arr = arr.filter(function(e){return e}); 

To remove empty values and Line breaks:

arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});

Example

arr = ["hello","",null,undefined,1,100," "]  
arr.filter(function(e){return e});

return

["hello", 1, 100, " "]
like image 22
Basit Avatar answered Jun 03 '26 08:06

Basit