Filter list with substring javascript? -


var ctr; var lst = ["", "xml", "w1", "w2"]; var ids = []; ctr = 0; (y = 0; y < lst.length; y++) {     if (lst[y].substring(0, 1) === "w") {         ids[y] = lst[y];         ctr = ctr + 1;     } } console.log([ids, ctr]); 

output: [[undefined, undefined, 'w1','w2'], 2]
expected output: [['w1','w2'],2]

what doing wrong? counter returned number have expected why getting 2 undefined in list? why happening?

you need use ids.push(lst[y]); instead of ids[y] = lst[y];, otherwise assigning values ids array @ random indexes - ie missing index values.

in code values assigned @ indexes 2 , 3 missing indexes 0 , 1 causing said output, because not assigning values ids in iterations - skipping iterations based on condition


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -