Obtain array repeats

-1
var a = {

edades = [12,15,16,2,12,45,60,15]

};

for(var i=0;i<a;i++) {

  console.log("Soy:" +i);
}

As a story if there are repeated numbers in array ages, and if they repeat only execute the instructions once (but only for that element) ?

In other words, if there were:

var b = [1,2,3,4,5,6,7,1];

The one that is repeated is 1, then it would show:

,2,3,4,5,6,7,1 and the first 1 not since it is repeated

    
asked by Eduardo Sebastian 21.07.2017 в 07:52
source

2 answers

2

The simplest way is to convert the Array into a data type "Set". A set (Set) does not contain repeated elements.

An example:

var a = [1, 1, 2, 3]
var b = new Set(a)
b.forEach(x => console.log(x))

Exit:

1
2 
3

Update

In that case, you can do it like this:

> var a = [1,2,3,4,5,6,7,1,1]
> var b = new Set()
> a.reverse().forEach(x => b.add(x))
> c = Array.from(b).reverse()

Value of c :

Array [ 2, 3, 4, 5, 6, 7, 1 ]
    
answered by 21.07.2017 / 10:52
source
2

In this code I use an associative array, whose key of the elements is the number of the array ages.

In the first pass of the array ages I create the associative array to control that in the second pass we only take out each element once.

var a = {

  edades : [1,2,3,4,5,6,7,1,1]

};

// Array para controlar si hemos sacado ya o no un elemento
var aListar = {};

// Array asociativo en el que me guardo si tengo que sacar el elemento en el listado (true) o si ya lo he sacado antes (false). La clave del array es el elemento origen
for (var i = 0; i < a.edades.length; i++) {
  aListar[a.edades[i]] = true;
}

var cad = ''; // Cadena para sacar los elementos finales en el mismo orden

// Empiezo a leer el array origen por detrás
for (var i = a.edades.length; i>0; i--) {
  if ( aListar[a.edades[i]] ) {
     // Su elemento del array asociativo está a true, por lo que no he listado este elemento aún
     aListar[a.edades[i]] = false;  // Marco para no sacarlo más veces
     cad = ',' + a.edades[i] + cad;
  }
}
document.write( cad );
    
answered by 21.07.2017 в 08:07