2

I want to reverse an array without using the built-in methods but the following function is not working:

function reverseArray(arr) {
  let brandNewArray = [];

  for (let i = arr.length - 1; i >= 0; i--) {
    brandNewArray += arr[i];
  }

  return brandNewArray;
}


reverseArray([1,2,3]);

2 Answers 2

4

Use push function instead of +=.

function reverseArray(arr) {
  let brandNewArray = [];
  for (let i = arr.length - 1; i >= 0; i--) {
    brandNewArray.push(arr[i]);
  }
  return brandNewArray;
}

console.log(reverseArray([1,2,3]));

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

Comments

3

Instead of += you need to push items into it. Using += at first time will assign to the brandNewArray a string, (as [] + 1 will give you "1"), with value of the last item. Then string concatenation goes and you got 321 as the final value of brandNewArray instead of array.

function reverseArray(arr) {
  let brandNewArray = [];
  
  for (let i = arr.length - 1; i >= 0; i--) {
     brandNewArray.push(arr[i]);
  }
  
  return brandNewArray;
}


console.log(reverseArray([1,2,3]))

Also you can use more compact version of your code

const reverseArray = arr => arr.reduce((acc, cur) => (acc.unshift(cur), acc), []);

console.log(reverseArray([1,2,3]))

Comments

Your Answer

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