0
// Using the .unshift() method
const reverseArray = arr => {
    let reversed = [];
    for (let i = 0; i < arr.length; i++) {
        reversed.unshift(arr[i]);
    }
    return reversed
}

if we want to reverse order the last element will become the first.How can this method reverse the order when it starts at first index?

4
  • unshift always adds to the first index, that's how. Commented Sep 20, 2021 at 5:11
  • For each element (starting with the first and ending with the last), prepend it to (i.e. add to the beginning of) the reversed array. This produced an array with the elements in reverse order from the original. Commented Sep 20, 2021 at 5:21
  • unshift adds the element at the first index of array and in this case reversed array is getting updated with that element when looping with a for loop at the start of reversed array. Have a look at developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… and understand how for loop works :) Commented Sep 20, 2021 at 5:24
  • reversedArray = [...originalArray].reverse() does the job too Commented Sep 20, 2021 at 5:44

2 Answers 2

2

Based on this:

The unshift() method adds new items to the beginning of an array, and returns the new length

So in each iteration you are adding item to the beginning of an array and when iteration is done you have reversed array.

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

1 Comment

@misssn Has your problem been solved?
0

"array.unshift()" is use to push items into array, you need to use "array.reverse()" to reverse the array.

const arr = [1, 2, 3];
arr.unshift(4, 5);
console.log(arr);
// reverse
arr.reverse(arr, "this is unshift");
console.log(arr, "this is reverse");

// output: arr [4, 5, 1, 2, 3]

3 Comments

I pretty sure they introduce reverse also in Codecademy, the question is, how unshift can reverse an array.
you mean your function will return reverse array right?
It's no my function, but yes, OP's function returns a reversed array, and they want to know how it works, not an alternative to their function.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.