Good day. I have two arrays, for example var arr = [1,2,3]; and var x = [1,2,3,4,5]; . And there is a script that removes the same elements of the array.

 for(var i=0;i<x.length;i++){ for(var j=0;j<arr.length;j++){ if(x[i]==arr[j]){ x.splice(i,1); } } } 

But the problem is that if you mix the elements of an array, for example, var arr = [1, 3, 2]; and var x = [5,3,1,2,4] , then as a result there may be elements that are repeated.

  • Often change the question. I do not have time to change the answer. Your task is to remove from the array x all the elements that are in the arr array? - Chubatiy
  • @Chubatiy I apologize, I need to find out from the array x indices of all elements that do not repeat with the elements arr - ItsMyLife
  • so what is the result expected? - Grundy

2 answers 2

About the following code

 for (var i = 0; i < x.length; i++) { var isExists = false; for (var j = 0; j < arr.length; j++) { if (x[i] == arr[j]) { isExists = true; } } if (!isExists) { //Ваш индекс i } } 

isExists match finding flag. Those. we iterate over the entire x array and compare with each element of the arr array.

If we find a match - we post a flag.

After checking, if the flag is not set (ie, no match is found) - then the current value of i is the index of a non-repeating element of the array x

  • I'm sorry, maybe I did something wrong, but if you take arrays var arr = []; var x = [ '1', '2', '3', '4', '5', '6', '7' ]; , it only issues 0,1,2,3 - ItsMyLife
  • Strange. Just completed - received as a result 0 1 2 3 4 5 6 - Chubatiy
  • I apologize, I forgot to remove one line in the big confusion, everything works fine, thank you so much! - ItsMyLife
 var a1 = [6,3,5,1,2]; var a2 = [1,2,4]; var result = []; a2.forEach(function(item) { var index = a1.indexOf(item); if (index !== -1) { result.push(index); } }); 

In this case, there is no need to use a nested for loop. This makes reading and debugging code very difficult.

  • you wrote your implementation of Array.prototype.filter - Grundy
  • And in underscore.js there is _.filter, which could be used. I just mean that the solution is much simpler than with two cycles for and an additional flag isExists. - user3240895
  • undescore - This is a library, and I meant the native function. this is why indexOf should not be used better either to Set or to collect an object from an array and check properties - Grundy
  • Set has poor support for IE (in some versions it is not implemented at all). - user3240895