Is it better to check if element exists in a JS array, or add it and then run _.uniq?
05:31 06 Mar 2017

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:

newArray.forEach(function(element){
  if (condition) {
    oldArray.push(element);
  }
})
oldArray = _.uniq(oldArray);

Maybe it doesn't really make a difference for small projects (and arrays), but I want to know what's best for a large scale project.

javascript arrays underscore.js