How to compare two arrays and if there is no element, then add to it from another?
Example:

arr [1,2,3,4,5]
tempDates [6,7,8]

If tempDates[i] !== arr[j] add to get

tempDates [1,2,3,4,5,6,7,8]

 for (var i = 0; i < tempDates.length; i++) { for (var j = 0; j < arr.length; j++) { if(tempDates.length == arr.length) { return true; } else if (tempDates.length !== arr.length) { if(tempDates[i] !== arr[j]){ tempDates.push(j); } } } } 
  • Do you need to check the condition of the problem if the arrays are the same length? Why do you double check the equality of length (if the first condition is not met, you go to the else. And again, "but are they not exactly equal", although you set a more stringent condition)? Why are you adding the index of an element, and not the element itself? - Vorobyov Alexander

2 answers 2

 var arr = [1,2,3,4,5], tempDates = [6,7,8]; for (var i = 0; i < tempDates.length; i++) { if (arr.indexOf(tempDates[i]) === -1) { arr.push(tempDates[i]); } } console.log(arr); 

    create a function to check the array elements for uniqueness

     function arrayUnique(array) { var a = array.concat(); for(var i=0; i<a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) a.splice(j--, 1); } } return a; } 

    let's execute this function from the combined arrays

     var res = arrayUnique(arr.concat(tempDates)); console.log(res); 
    • one
      if the source array was [1,1,1] this method will not work - Grundy