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

109
Visualizações
Array JavaScript problem. First element go to the last position

I have function that get array, and return array with power 2 of every array element. This is source code

const firstArr = [1, 2, 3, 7, 4, 9];

function arrayPow(arr) {
    const outputArray = [];
    arr.forEach(el => {
        console.log(el);
        outputArray.splice(-1, 0, el**2);
    })
    return outputArray;
}

console.log(arrayPow(firstArr));

I got this as output:

script.js:8 1
script.js:8 2
script.js:8 3
script.js:8 7
script.js:8 4
script.js:8 9
script.js:14 (6) [4, 9, 49, 16, 81, 1]

Scedule of elments correct in loop. But now in array, there first element, in some reson, stay in the end. I tried to delete "1" from firstArr, then "4" go to the last position. Why?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Putting -1 in your splice means you insert before the last element in the array. When the array is empty, it simply is added as the only item.

Following, you then insert before the last element of the array, hence every subsequent iteration will add the item as the second last element.

I would just use ES6 magic:

const firstArr = [1, 2, 3, 7, 4, 9];
const arrayPow = (arr) => arr.map(i => i**2)
console.log(arrayPow(firstArr))

about 4 years ago · Juan Pablo Isaza Relatório

0

Use this code, it will work like charm!

const firstArr = [1, 2, 3, 7, 4, 9];

function arrayPow(arr) {
    return arr.map(v => v ** 2);
}

console.log(arrayPow(firstArr));
about 4 years ago · Juan Pablo Isaza Relatório

0

If I am understanding your question correctly, you want to raise each element in the array by the power of 2? If so, I am unsure why you are splicing the array. You could try the following:

function arrayPow(arr) {
    const outputArray = [];
    arr.forEach(el => {
        outputArray.push(el**2);
    })
    return outputArray;
}

const test = [1,2,3]
console.log(arrayPow(test))

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