Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!