Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
Stop duplicates in an array

Problem has been solved

What I need is if I declare n as 4. I need 4 unique coordinates and push them to array, here is my code that can produce duplicates:

function entriesToDel(n) {

        var array = [];

        for (let i = 0; i < array.length; i++) {
            var row = Math.round(3*Math.random());
            var col = Math.round(3*Math.random());
            var output = [row,col]; 
            array.push(output);

    }

    return array;
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

What you can do is simply put a condition based checking for the coords.

e.g. You can do something like,

function entriesToDel(n) {

    var array = [];

    for (var i = 0; i < n; i++) {
        const repeat = () => {
            var row = Math.round(3 * Math.random());
            var col = Math.round(3 * Math.random());
            var coords = [row, col];

            let sameEntry = array.find(i => i[0] === row && i[1] === col)
            if (sameEntry) {
                repeat();
            } else {
                array.push(coords);
            }
        }
        repeat();
    }
    console.log(array);
    return array;
}

about 4 years ago · Juan Pablo Isaza Relatório

0

Instead of creating the coordinates randomly, shuffle an array with all 3x3 coordinates and pick the first n of them:

function shuffle(a) { // Generic shuffle function
    for (let i = a.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        let x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}

function entriesToDel(n) {
    // Generate all possible coordinates in a 3x3 grid
    let coord = Array.from({length: 3}, (_, i) =>
        Array.from({length: 3}, (_, j) => [i, j])
    ).flat();
    
    // Shuffle and select
    return shuffle(coord).slice(0, n);
}

console.log(entriesToDel(4));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can just change your for loop into a while loop, and just terminate when the array.length is equal to your parameter.

You can use Arrray.some() to check if you already have the coordinate.

eg.

function entriesToDel(n) {
    var array = [];
    while (array.length < n) {
        var row = Math.round(3*Math.random());
        var col = Math.round(3*Math.random());
        var coords = [row,col]; 
        if (!array.some(([r,c]) => 
           r === row && c === col))
              array.push(coords);
    }
    return array;
}

console.log(entriesToDel(4));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda