javascript array clean function -
simple function clean array if has null or empty values, if have:
[ 'click1', 'click2', null, '', '', 'submitform' ]
...it return:
[ 'click1', 'click2', 'submitform' ]
here code:
function squeakyclean(arr) { (var = 0; < arr.length; i++) { if (arr[i] == null || arr[i] == '') { arr.splice(i); }; }; return arr; }
i have loop check each value in array , if statement see if equal null or , empty string, if used array splice method remove value , return clean array outside loop.
it works if enter array no empty strings or null values, if enter [ 1, , 2, 3, 0, -1, 1.1 ]
returns [1]
should not do. missing here?
ps: have looked how other people solved using without loop , splice method, interested in how solve using these two.
your code fine apart use of .splice
method must specify number of items on index delete.
example: array.splice(index, numberofitemsfromindex);
therefore fix code should simple as:
function squeakyclean(arr) { (var = 0; < arr.length; i++) { if (arr[i] == null || arr[i] == '') { arr.splice(i, 1); }; }; return arr; }
Comments
Post a Comment