I have an array of numbers and dynamically adding new numbers to that array in for loop. But I need to avoid adding values that already exist in array. Is there a JS native way to check the presence of some value in array without doing 2nd nested loop. I don’t want to use nested loop because the size of array may vary up to 10000
Share
You can easily avoid a for loop by using a while loop. [Pause for laughter…] But seriously, even the built-in
Array.indexOf()method (supported by most browsers) probably uses a loop internally.You could use a plain object instead, and add each number to the object as a property, then afterwards take the values from the object and put them in an actual array (or just use them in the object if that is convenient). Then you only have to loop through the “up to 10000” numbers once at the end:
After which
numbersArraycontains unique numbers only. The if test with.hasOwnProperty()is “optional” depending on your point of view.Within the first loop you could check if
numbersObjalready holds thecurrentNumber:Or just (over)write it every time like I did in the first code block.