I write my bike to remove the same elements of the array. As if during the output to the console, duplicates are not caught, that is, everything is displayed as it should (1, 11, 2, 4, 5, 3). But at the same time, nothing falls into the resulting res array. Help fix

var res = []; var a = [1, 1, 11, 2, 4, 2, 5, 3, 1]; var N = a.length; for (i = 0; i < N; i++) { f = 1; for (j = 0; j < N; j++) if (a[i] == a[j] && i != j) { f = 0; break; } if (f == 1){ console.log(a[i]); //в консоле(1,11,2,4,5,3) res.push(a[i]) // в итоговом массиве 1,1,11,2,4,2,5,3,1 -----что не верно } } } 
  • the second if you just need to get out of the inner loop for - Grundy

3 answers 3

Honestly, I don't want to watch your bike. Yes, he and the console displays duplicates. I do not know how you checked.

But, kmk, it's easier to do this:

 var arr = [1, 1, 11, 2, 4, 2, 5, 3, 1]; var set = new Set(arr); arr = Array.from(set); console.log(arr); 

Set objects allow you to store unique values ​​of any type, both primitives and other types of objects. (like browsers support)

Array.from () creates a new Array instance from an array-like or iterable object.

  • Not bad, informative for me) - Yuri

Getting unique items through Array.filter :

 var arr = [1, 1, 11, 2, 4, 2, 5, 3, 1]; arr = arr.filter(function(itm, i, a) { return i === a.indexOf(itm); }); console.log(arr); 

Perfectly supported by browsers (IE9 +) in contrast to the beautiful and modern way @AlekseyShimansky , which, unfortunately, does not work even in IE11 (due to Array.from ), if IE support is important.


If IE support is not important or Babel is used, you can do the same through the arrow function:

 var arr = [1, 1, 11, 2, 4, 2, 5, 3, 1]; arr = arr.filter((itm, i, a) => i === a.indexOf(itm)); console.log(arr); 

  • Usually the code through Babel is banished, so Array.from() is not a problem. - neluzhin
  • one
    Well, who is like that? In any case, if you still do it through the arrow function, then the code will not differ much in conciseness from the accepted answer. - Vadim Ovchinnikov

Update 3 : I suggest you this solution:

 $(function() { var a = [1, 1, 11, 2, 4, 2, 5, 3, 1]; var b = []; for(var i = 0; i < a.length; i++){ var status = 1; for(var j = 0; j < b.length; j++){ if(a[i] == b[j]){ status = 0; }; }; if(status == 1){ b[b.length] = a[i]; }; }; console.log(a); console.log(b); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

  • And what to do if you need not to delete the elements in the old array and insert them into the new? Can you write? - J.Joe
  • @ J.Joe, hold on - Yuri
  • , not much else, it should be an array of 1, 11, 2, 4, 5, 3 and now I'm dumb :( - J.Joe
  • @ J.Joe, did you bring it in? - Yuri
  • @ J.Joe, look, I updated the answer. Why don't you initially copy the array and not subtract it from the second? - Yuri