0

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?

  • Try like, `const powers = firstArr.map(num => num ** 2);` instead of pushing into another array.. – Maniraj Murugan Nov 24 '21 at 04:56
  • Use `outputArray.push(el ** 2)`. If you add a debugger and check the array after each iteration, you'll get the issue. It adds the value at last but one postion each time. – adiga Nov 24 '21 at 05:03
  • this is the best write up on all the answers you are going to get here, map and for-each function differently https://stackoverflow.com/a/9329476/14916414 – cubesareneat Nov 24 '21 at 05:04

3 Answers3

2

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))
Steve
  • 4,372
  • 26
  • 37
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));
Sateesh
  • 1,327
  • 9
  • 12
  • 3
    Good lord that's such a heavy, convoluted way of doing it. You can literally get a squaring function that ALSO let's you specify a different power to raise to if you want in one line: `const arrayPow = (arr, pow = 2) => arr.map(el => el**pow);` – Jayce444 Nov 24 '21 at 05:01
  • 1
    That original answer was like killing a fly with a shotgun. – Steve Nov 24 '21 at 05:07
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))
Kevin
  • 9
  • 2