There is an array

var array = ['one', 'two', 'three', 'one', 'two', 'one', 'three', 'one']; 

and you need to remove duplicate values, if any, so that in this example it would turn out

 var array = ['one','two','three']; 

I tried it this way, but every second one is deleted.

 for (var i=0; i<array.length; i++){ var compare = array[i]; for (var j=0; j<array.length; j++){ if (compare == array[j]){ delete data_search[j]; } } } 
  • Look here . - Roman Grinyov
  • one
    ES6 function uniq(a) { return Array.from(new Set(a)); } function uniq(a) { return Array.from(new Set(a)); } - Alexey Shimansky

3 answers 3

If you use ES6:

 function uniq(a) { return Array.from(new Set(a)); } var array = ['one','two','three','one','two','one','three','one']; console.log(uniq(array)); 

And you can also see a bunch of ways from English SO , which makes no sense here, because there are a lot of them and they are described there in detail

  • somehow boring and not interesting :) - Grundy
 function unique(arr) { var obj = {}; for (var i = 0; i < arr.length; i++) { var str = arr[i]; obj[str] = true; } return Object.keys(obj); } 

Here read in more detail.

  • And why did you use exactly objects and not purely arrays and functions of working with them? What is the general benefit of using objects instead of arrays? Absolutely everything can be repeated in both versions, right? - Telion
  • @Levelleor, the object here serves as a hash, since it does not allow adding several identical properties to it. Thus, the problem is solved in a single pass, as opposed to an array, where another pass is needed for each element to determine the uniqueness - Grundy
  • My choice in the direction of objects was made because of the simplicity and speed of work. The logic is simple. array [key: value] when meeting a duplicate key is simply overwritten the value. In small arrays the difference is absolutely not noticeable. - Shadow33
  • @Grundy And what is the logic of the object? An array is a key value and around a circle of infinity, and objects are similar to classes in C ++, do they store values ​​in certain "keys"? According to the link that you sent, I did not find much information ... - Telion
  • @Levelleor. An object in javascript is a regular associative array or, in other words, a "hash". here in more detail - Shadow33
 var array = ['one', 'two', 'three', 'one', 'two', 'one', 'three', 'one']; for (var i=array.length-1; i>=0; --i) { var compare = array[i]; for (var j=i-1; j>=0; --j) { if (compare == array[j]){ array.splice(j, 1); --i; } } }