on-internet
← Community

Is it better to check if element exists in a JS array, or add it and then run _.uniq?

Stack Overflow ·

Say you have an array of unique values and want to push new elements from another array, that meet a condition, without creating duplicates. E.g. newArray.forEach(function(element){ if (condition) { oldArray.push(element); } }) With regards to performance in Javascript, is it better to check, in every iteration of the loop, if the element exists already before pushing to the array, or to add all the elements that meet the condition, and then run _.uniq from underscore.js? newArray.forEach(function(element){ if (condition && !oldArray.includes(element)) { oldArray.push(element); } }) versus: ne

Comments

Sign in or sign up to comment and upvote.

No comments yet.