Remove duplicate elements from an array

2

Read the question before marking it as repeated, thank you.

What I need is that if there are duplicate elements in the array, delete them all. The array is something similar to this:

var array = [[1,2],
             [2,3], // repetido
             [3,4],
             [4,5],
             [2,3], // repetido
             [5,6],
             [6,7], // repetido
             [6,7], // repetido
             [7,8]]

so it would look like this:

var array = [[1,2],
            [3,4],
            [4,5],
            [5,6],
            [7,8]]

There may be at least 1000 values in the array, so nesting a for loop in another, and checking value for value is not efficient, the browser is closed and the processor is set to 90%

    
asked by gmarsi 30.09.2018 в 20:07
source

2 answers

1

The iteration of the Array must occur only once, for each iterated element we must evaluate in a new array if it already exists or not.

The explanation is in the code, the functions that are used are some ( ) to verify that it exists or not in the array, and splice ( ) to remove duplicate array elements.

var array = [[1,2],[2,3],[3,4],[4,5],[2,3], [5,6],[6,7], [6,7], [7,8]]
let newArray = [];
array.forEach(elem=>{
  // verificamos si existe en el nuevo array , comparando su dos componentes
  // posición 0 y 1 , si no existe, añadimos el emenento al array
  if(!newArray.some(valor=> valor[0] === elem[0] && valor[1] === elem[1]))  
     newArray.push(elem);
  else {
	//caso contrario buscamos las coincidencias para eliminarlas
     newArray.forEach((valor,index)=> {
	//iteramos el array de no duplicados y eliminamos
	//los valores. con splice 
	if(valor[0]=== elem[0] && valor[1] === elem[1]) newArray.splice(index,1);
     });
  }
})
console.log(newArray);
    
answered by 30.09.2018 / 20:44
source
0

You can try this:

var array = [[1,2],
             [2,3], // repetido
             [3,4],
             [4,5],
             [2,3], // repetido
             [5,6],
             [6,7], // repetido
             [6,7], // repetido
             [7,8]];
             
const eliminarRepetidos = (array) => {
    var unicos = [];
    var itemsEncontrados = {};
    for(var i = 0, l = array.length; i < l; i++) {
        var stringified = JSON.stringify(array[i]);
        if(itemsEncontrados[stringified]) { continue; }
        unicos.push(array[i]);
        itemsEncontrados[stringified] = true;
    }
    return unicos;
}

let arrayFiltrado = eliminarRepetidos(array);
console.log(arrayFiltrado);

The simplest way I could think was to serialize the value of the array and store if it had already been found. Source

    
answered by 30.09.2018 в 20:42