Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
Looping over javascript array not producing correct results

I am working on a program that should set a string answer to a specific value. I have tried reversing the order of the loop, setting global variables, but something is off in the way the arrays are being processed.

The code below

        console.log("The value of the dlArray is")
        console.log(dlArray)
        console.log("The value of the elArray is")
        console.log(elArray)
        dlArray = shuffle(dlArray);
        for (let i = numberOfInputs; i < elArray.length+numberOfInputs; i++){
            html += '\t\t\t\t\t\t<div id=\'s';
            id   = (1+i-numberOfInputs);
            html += id;
            html +='\' class=\'draggyBox-small ui-draggable\'>\n';
            html += '\t\t\t\t\t\t\t'
            html += elArray[i-numberOfInputs]
            html += '\n';
            html +='\t\t\t\t\t\t</div>\n';
        }
        console.log("The value of the dlArray is")
        console.log(dlArray)
        console.log("The value of the elArray is")
        console.log(elArray)

        function shuffle(a){
            for(let j,i=a.length;i>1;){
              j=Math.floor(Math.random()*i--);
              if (i!=j) [a[i],a[j]]=[a[j],a[i]]
            }
            return a
        }

produces the Actual output

*****************************************
The value of the dlArray is
word_match.js:99 (4) ['d1', 'd2', 'd3', 'd4']
word_match.js:100 The value of the elArray is
word_match.js:101 (4) ['k1', 'k2', 'k3', 'k4']
word_match.js:113 The value of the dlArray is
word_match.js:114 (4) ['d4', 'd3', 'd1', 'd2']
word_match.js:115 The value of the elArray is
word_match.js:116 (4) ['k1', 'k2', 'k3', 'k4']
word_match.js:198 k1:d4 k2:d3 k3:d1 k4:d2 

The expected output should be

*****************************************
The value of the dlArray is
word_match.js:99 (4) ['d1', 'd2', 'd3', 'd4']
word_match.js:100 The value of the elArray is
word_match.js:101 (4) ['k1', 'k2', 'k3', 'k4']
word_match.js:113 The value of the dlArray is
word_match.js:114 (4) ['d4', 'd3', 'd1', 'd2']
word_match.js:115 The value of the elArray is
word_match.js:116 (4) ['k1', 'k2', 'k3', 'k4']
word_match.js:198 k1:d1 k2:d2 k3:d3 k4:d4 

Any help understanding where the error in this for loop is coming from would be greatly appreciated. Thank you.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Since you are not giving a lot of details, I would assume the dlArray is always in reverse order.

This would be another way of doing it without a for loop:

const elArray = ['k1', 'k2', 'k3', 'k4'];
const dlArray = ['d4', 'd3', 'd2', 'd1'];

dlArray.reverse();

const answers = elArray.map((value, index) => `${value}:${dlArray[index]}`);

// Alternative without mutating the original dlArray
//
// const reversedDl = [...dlArray].reverse();
// const answers = elArray.map((value, index) => `${value}:${reversedDl[index]}`

console.log(elArray);
console.log(dlArray);
console.log(answers.join(' '));

UPDATE After your changes to the original post, I understand that you need to sort the dlArray before doing it because it might be shuffled (?)

An updated version would be:

const elArray = ['k1', 'k2', 'k3', 'k4'];
const dlArray = ['d3', 'd2', 'd1', 'd4'];

// Without mutating the original dlArray
const sortedDlArray = [...dlArray].sort();
const answers = elArray.map((value, index) => `${value}:${sortedDlArray[index]}`);

// Alternative with mutating the original dlArray
// dlArray.sort();
// const answers = elArray.map((value, index) => `${value}:${dlArray[index]}`);

console.log('elOriginal:', elArray);
console.log('dlOriginal:', dlArray);
console.log('dlSorted:', sortedDlArray);
console.log(answers.join(' '));

You may update the ${value}:${sortedDlArray[index]} to include whatever classes you need there:

eg.

elArray.map(
    (value, index) => 
        `<div id="wrapper-${index}" class="whatever-class you need here">${value}:${sortedDlArray[index]}</div>`
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

elArray = ['k1', 'k2', 'k3', 'k4'];
dlArray = ['d4', 'd3', 'd2', 'd1'];

answer = "";

console.log("*****************************************");
console.log(elArray)
console.log(dlArray)
for (let i = 0; i < dlArray.length; i++) {
  answer += elArray[i];
  answer += ':';
  answer += dlArray[(dlArray.length - 1) - i];
  answer  += ' '
}
console.log(answer)

        

I made some assumptions as you did not provide some of the supporting details. As you can see here though I simply just subtracted the current i to get the reverse positioning.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda