C
Second https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf , indexOf returns the first index that has the informed element. Ex:let array = [ 1, 2, 3, 1, 4];
console.log(array.indexOf(1)); // 0Number 1 is in two array positions (in zero and 3 positions - remember that the first position is zero, the second is 1, etc), but array.indexOf(1) returns 0, since it is the index corresponding to the first occurrence of 1 inside the array.Then array.indexOf( array[ i ] ) verifies the first position in which the element occurs array[i] (i.e. the first position in which the position element occurs i). If that position differs from i, means that the element is duplicated.Using our above array as an example: when i is equal to 3, array[i] will be number 1 (the second occurrence of number 1). Only array.indexOf( array[ i ] ), as we have seen, returns zero, which is different from 3, and so there I detected that the element is repeated.So actually if detects the first occurrence of each element. If it is different, it does not enter if, because then I know that it is duplicated and I do not need to insert the element again into models.From ES6, you can use one https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set to get the same result:let array = [1,1,1,2,3,4,4,5];
let models = Array.from(new Set(array));
console.log(models); // [1, 2, 3, 4, 5]
// ou usando spread syntax: https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Operators/Spread_syntax
models = [... new Set(array)];
console.log(models); // [1, 2, 3, 4, 5]Finally, it is worth remembering that indexOf always https://tc39.es/ecma262/#sec-array.prototype.indexof , that is, for each element of the array, I will be going through the same array several times, from the beginning to the first occurrence of the element (a variation of the https://www.joelonsoftware.com/2001/12/11/back-to-basics/ ).That's why this algorithm can become quite inefficient as the array increases (for small arrays it won't make so much difference, but for larger arrays it can be a problem, especially if it doesn't have many repeated elements).Another approach would be to have an object to keep the elements that have already been found:let array = [1,1,1,2,3,4,4,5];
let models = [];
let encontrados = {};
for (var i = 0; i < array.length; i++) {
// só adiciono quem ainda não foi encontrado
if (encontrados[array[i]] === undefined){
encontrados[array[i]] = true;
models.push(array[i]);
}
}
console.log(models);Making a basic test with an array of over 10,000 elements, https://jsbench.me/04k7ys87ck/2 . But for a small array, https://jsbench.me/n2k7yslq9f/1 .