0

In general, in the following code, my goal was to store the values of the array from end to begining in a new array, then display it as a number, Of course, in the meantime, I doubled the value of each array cell.

I want to know is there an easier way?

let firstArray = [1, 2, 3];
const secondArray = [];
firstArrayLength = firstArray.length;

let i = 0;
let y = 0;

while (i < firstArrayLength) {
  secondArray.push(firstArray.pop());
  i++;
};

secondArrayLength = firstArrayLength;

while (y < secondArrayLength) {
  if (y == 0) {
    secondArray[y] = secondArray[y] * 100;
    secondArray[y] = secondArray[y] * 2;
  }
  if (y == 1) {
    secondArray[y] = secondArray[y] * 10;
    secondArray[y] = secondArray[y] * 2;
  }
  if (y == 2) {
    secondArray[y] = secondArray[y] * 1;
    secondArray[y] = secondArray[y] * 2;
  }
  y++;
}

let sum = 0;

for (let i = 0; i < secondArray.length; i++) {
  sum = sum + secondArray[i];
}

console.log(sum);

3
  • Code review has its own site -> codereview.stackexchange.com Commented Aug 27, 2021 at 13:57
  • You're not doing anything with secondArray other than sum its elements. There's no need for that. You can get sum also with just the elements in firstArray. Commented Aug 27, 2021 at 13:59
  • I took the liberty to replace the code block with a snippet. The additional markup was not relevant for the topic of your question, hence I removed it (and replaced the only interaction with it with a console.log(sum)) Commented Aug 27, 2021 at 14:03

1 Answer 1

1

A solution using one array, Array.reverse() and map() (By mutating the original array):

let firstArray = [1, 2, 3];

firstArray.reverse(); // --> [3, 2, 1]

let sum = '';

firstArray.map(i => {
  sum += i*2+''
});

console.log(sum); // --> 642

// if you need integer value of sum
let int_sum = parseInt(sum)

A solution without mutating the original array:

    let firstArray = [1, 2, 3];
    let sum = '';
    
    firstArray.slice().reverse().map(i => {
      sum += i*2+''
    });

    console.log(firstArray); // --> [1, 2, 3]
    console.log(sum); // --> 642
    
    // if you need integer value of sum
    let int_sum = parseInt(sum)

Sign up to request clarification or add additional context in comments.

2 Comments

Why is sum a string (to be then parsed and stored as an integer in int_sum)? o.O
that was perfect -pukshan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.