how to find repeated in a javascript array [duplicated]

2

Hello Friends given an array:

var x = [1,9,2,1,5,6,2,9];

How could you identify the elements that are repeated in the array x and put those repeated in another array?

I know I have to go through it with for (i=0; i<x.length;i++) and save it in another array with a push, but I would not know how to compare each element with all the elements of the array.

I appreciate suggestions. I'm a beginner in Javascript.

Thank you for your contributions

    
asked by Ing Carlos Tello 29.05.2018 в 04:32
source

3 answers

6

If, by removing, you mean to eliminate them:

var x = [1,1,2,3,4,5,6,6,6,7]
var uniqs = x.filter(function(item, index, array) {
  return array.indexOf(item) === index;
})
console.log(uniqs); // [ 1, 2, 5, 6 ]

filter ignores the elements that return a false, therefore if when you ask what position an item is in and it does not correspond to the index it has in the current array it means that it is repeated.

    
answered by 29.05.2018 в 06:00
2

Hi, you can use the Set to remove repeated elements and then get an Array like this: [...unicos]

let arr = [1,2,3,3,4,5,5,5,5,5];

let unicos = new Set(arr);

console.log("Unicos: ", [...unicos]);

The set preserves the elements in order of insertion and can be iterated in the following way:

for (let item of mySet) console.log(item);
    
answered by 29.05.2018 в 06:03
1

If what you want to get the repeating elements of an array you can try the following:

var elementos = [1,1,3,5,6,4,9,5,3,5,7,9,0,1];
var repetidos = [];
var temporal = [];

elementos.forEach((value,index)=>{
  temporal = Object.assign([],elementos); //Copiado de elemento
  temporal.splice(index,1); //Se elimina el elemnto q se compara
  /**
   * Se busca en temporal el elemento, y en repetido para 
   * ver si esta ingresado al array. indexOf returna
   * -1 si el elemento no se encuetra
   **/
  if(temporal.indexOf(value)!=-1 && repetidos.indexOf(value)==-1)      repetidos.push(value);
});

console.log(repetidos);
    
answered by 30.05.2018 в 01:05