I have the following 2 array:
Array 1:
var datos1=[1,2,3,4,5,6,7];
Array 2:
var datos2=[3,5,7];
What I want is to fill a new array where the data that is not present in it is saved, var datos2
for example: [1,2,4,6]
, I am trying the following way but it is not how I would like it to be:
for(var j=0;j<datos1.length;j++){
for(var k=0;k<datos2.length;k++){
if(datos1[j]!=datos2[k]){
datosNoRepetidos[j]=datos2[k];
}
}
}
Thank you very much for the help.
I know you got a very well explained and functional answer but this purpose could also be achieved with the filter method to create a new one
array
based on the result returned by the condition. That in the secondarray
no ! this iterated element is included. (the)let's see... let's analyze your algorithm...
The second for has the idea... but it's not complete. If you save the value in the dataNotRepeated array the first time it is not repeated, then you will save all the values of the second array. forever.
In other words, you compare 1 with 3... obviously they are not the same... so you already record 3. The question would be why?
to get started? you should go through the arrays in reverse order, that is, look for the ones you want to know if they are there or not, in the other... something like that...
Now, this obviously still doesn't solve your problem...because it's missing...something that says it's not anywhere in the second array...
For that... let's add a flag...
Suppose that it is not... in this way... if it is not... it will never be true... to make it true... we do the following...
So let's add an if, which tells us whether to add it or not.
If it ever became true... then it's in some position, and it's of no use to us.
Now... we are missing something else... dataNoRepeats[j] is not right... we have to save in the last position of that array, not in the same position of the arrays that we are traversing... so... let's add a counter.
You can do it in a simple way with lodash's "union" function: https://lodash.com/docs/4.17.5#union
The code would be like this.