Capture repeated elements from a Javascript array

Asked

Viewed 3,248 times

6

I need to remove the repeated values of a vector and play these repeated values in another vector, I found this code that removes the repeated values, but I do not know how to capture them, and I am not understanding very well how the filter is acting to remove the repeated values. Can anyone explain to me in more detail what is happening in the code?

var aux = vetor.filter(function(elemento, i) {
    return vetor.indexOf(elemento) == i;
})

2 answers

7


Below is a way to capture all repeaters by following the code that was passed on:

var repeated = [];

var aux = vetor.filter(function(elemento, i) {
    if(vetor.indexOf(elemento) !== i) {
        repeated.push(elemento)
    }
    return vetor.indexOf(elemento) == i;
})

What that code does?

The vetor.indexOf(elemento) !== i checks if the element being searched for in the array is found in the same position as it is currently, if you have any element identical to it in the position of the indexf it will be different and will not be returned in the filter.

When this happens it is added in the repeated array the repeated element.

4

To make it easier to understand, you can try doing this in two operations, first creating the array of repeated elements, and then creating an array of unique elements. An example of how to find the repeaters:

var arr = [9, 9, 111, 2, 3, 4, 4, 5, 7];
var sorted_arr = arr.slice().sort(); // Ordenando o array. 
var results = [];
for (var i = 0; i < sorted_arr.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        results.push(sorted_arr[i]);
    }
}

An example of how to create an array without repetitions:

var arr = [1,2,2,3,4,5,5,5,6,7,7,8,9,10,10];

function arrayNovo(arr){
    var tmp = [];
    for(var i = 0; i < arr.length; i++){
        if(tmp.indexOf(arr[i]) == -1){
        tmp.push(arr[i]);
        }
    }
    return tmp;
}

console.log(arrayNovo(arr));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.