javascript - Empty elements in JS array declaration -


it's first question here, after have been reading years, nice me please.

i'm having trouble array management in js/jq.

i have array several elements, processed $.each function. want extract matching elements array , return array. reason (don't know if it's because array declaration, jquery.each function...) i'm having first empty element.

i think i'm making more difficult understand it's, made jsfiddle.

var arr = new array(); $.each([1,2,3], function(index,element){     if (element == 2){         arr[index] = element;     } }); 

arr must have 1 element, arr.length returns 2 because first array slot empty.

here fiddle http://jsfiddle.net/moay7y95/

i'm sure it's simple , little stupid thing, i've not been able find answer.

thanks in advance!

best solution: use .filter

var arr = [1, 2, 3].filter(function(value){     return value == 2 }); 

if return value true, element included in returned array, otherwise ignored. pure js, don't need jquery. see documentation .filter

your problem: use .push

try using .push method on array (see mozilla's documentation).

var arr = new array(); $.each([1,2,3], function(index,element){     if (element == 2){         arr.push(element);     } }); 

the .push method dynamically grow array elements added.

your problem value of index inside function reference point in initial array. means if @ returned array, find [undefined, 2] , length returning 2. if condition element == 3 have 2 empty slots.

alternatively: use .grep

another jquery method $.grep. see http://api.jquery.com/jquery.grep/

var arr = $.grep([1, 2, 3], function (value) {     return value == 2 }); 

this jquery's implementation of javascript's .filter.


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -