Home > Mobile >  Array JavaScript problem. First element go to the last position
Array JavaScript problem. First element go to the last position

Time:11-24

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?

CodePudding user response:

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))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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));

CodePudding user response:

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))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related