3

Quick JavScript question. In the following pieces of code I'm reversing the array arr that's being passed to the function reverseArray.

In the first piece of code, it looks like that the local variable arr keeps changing even though inside the loop I am operating on the variable newArr which hold the initial value of arr. Hence the loop fails when arr.length reaches the values 3.

function reverseArray (arr) {
    var newArr = [];
    var inArr = arr;
    console.log(inArr);
    for (i = 0; i < arr.length; i++) {      
        newArr[i] = inArr.pop(i);       
    }   
    return newArr;
}
reverseArray(["A", "B", "C", "D", "E", "F"]);

// OUTPUT: ["F", "D", "E"]

On the other hand, if I store arr.length on local variable numArr, then it works perfectly and reverses the array.

function reverseArray (arr) {
    var numArr = arr.length;    
    var newArr = [];    
    for (i = 0; i < numArr; i++) {      
        let inArr = arr;
        newArr[i] = inArr.pop(i);       
    }
    return newArr;
}

reverseArray(["A", "B", "C", "D", "E", "F"]);

// OUTPUT: ["F", "E", "D", "C", "B", "A"]

What am I missing?

3
  • pop() doesn’t take any arguments. Commented Jun 23, 2018 at 9:36
  • why do you have three arrays? the assingment of an array assigns the object reference. the handed over array is mutated, too. Commented Jun 23, 2018 at 9:38
  • @Ry- you're right but in this case, that doesn't make any difference. Commented Jun 23, 2018 at 18:00

10 Answers 10

3

pop (MDN, spec) is a mutator method: It changes the state of the array you call it on. So naturally, inArr.pop(1) modifies arr (in your first example), since inArr and arr both refer to the same array.

Probably worth noting as well that pop doesn't accept any parameters, so that 1 doesn't do anything.

In your first example, your best bet is to just assign another variable (say, j) the initial value arr.length - 1 and use arr[j] to get the value, then decrease j as you increase i. (Also, no point to inArr, and you need to declare i to avoid what I call The Horror of Implicit Globals:

function reverseArray (arr) {
    var newArr = [];
    for (var i = 0, j = arr.length - 1; i < arr.length; i++, j--) {      
        newArr[i] = arr[j];
    }   
    return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));

You can also just use arr[arr.length - i - 1] rather than a second variable:

function reverseArray (arr) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {      
        newArr[i] = arr[arr.length - i - 1];
    }   
    return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));

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

4 Comments

Makes sense, but then why when (in the second snippet) I assign numArr = arr.length, numArr doesn't keep changing while arr decreases.
@leonardofed - Because numArr has no connection whatsoever to arr. numArr = arr.length copies the value of length into numArr. There's no ongoing link after that.
The second solution is not working for the numbers. example: [0,1,2,3,4,5].
@VenuMadhav - The second solution does work for that array (or any other): jsfiddle.net/tjcrowder/nu4pxLkr
3

You could take a copy of the array and use the length of the copy for checking the next pop/push command.

function reverseArray(array) {
    var newArr = [],
        inArr = array.slice();    // take copy of primitive values

    while (inArr.length) {        // check decrementing length
        newArr.push(inArr.pop());
    }
    return newArr;
}

console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));

To fullfill the condition, you could use a for statement as well.

function reverseArray(array) {
    var newArr = [],
        inArr = array.slice();    // take copy of primitive values

    for(; inArr.length; ) {       // check decrementing length
        newArr.push(inArr.pop());
    }
    return newArr;
}

console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));

1 Comment

What purpose does using a for where a while is appropriate serve?
1

Here It Goes using two For Loops:

let arr = [1, 12, 15, 16, 78, 89, 53];
for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
    let c, a, b;
    b = arr[i];
    arr[i] = arr[j];
    arr[j] = b;
  }
}
console.log(arr);

1 Comment

just ignore variables c and a
1

Example:

fruit=['banana', 'orange', 'mango', 'lemon'] //array
    
z=[] //empty array

for(i=(fruit.length-1);i>-1;i--){    
  z.push(fruit[i])
}

//i>-1 because the index of array ends at 0
    
console.log(z)

Comments

1
function reverseArray(a) {
    let arrayLength = a.length
    for (let i = 0; i< arrayLength/2; i ++){
      let temp =  a[i]
    a[i] = a[arrayLength -(i+1)]
    a[arrayLength - (i+1)] = temp
}
return a
}
reverseArray([1,2,3,4,5,6,7,8,9]) //expect: 9,8,7,6,5,4,3,2,1

1 Comment

actually, we can let i < Math.floor(arrayLength) to eliminate the middle element. This case is to not change position of itself
0

The problem with your first function is that when you pop an element from an array arr its actually decreasing the length of your array arr. That is why you see less results then the original number of elements.

so your code worked like this

1st pass: i=0 and arr.length = 6; // 0<6 true
2nd pass: i=1 and arr.length = 5; // 1<5 true
3rd pass: i=2 and arr.length = 4; // 2<4 true
4th pass: i=3 and arr.length = 3; // 3<3 false and it does not execute

so you see only three results.

2 Comments

The OP could do that, but it's pointless to modify the source array (or a copy of it) when building the reversed array.
@T.J.Crowder i have updated my answer. thanks for pointing out.
0

You could try to use this code:

function reverseString(str) {
    var newString = "";
    for (var i = str.length - 1; i >= 0; i--) {
       newString += str[i];
    }

    return newString;
}

Comments

0
let input = ["A", "B", "C", "D", "E", "F"];
let output = [];

for(let i = 1; i <= input.length; i++) {

    // determine correct array index in respect to the current iteration
    let index = input.length - i;

    // push to new array
    output.push(reverse[index]);
}

// verify result
console.log(output);

1 Comment

While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn and eventually apply that knowledge to their own code. You are also likely to have positive feedback/upvotes from users, when the code is explained.
0

This is similar code to reverse an Array.

function reverseArray(arr) {
    let newArr = [];
    for (i = arr.length - 1; i >= 0; i--) {
        newArr.push(arr[i]);
    }
    return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));
//output: ["F","E","D","C","B","A"]

Comments

0
    function reverseString(str) {
    var revArr = [];
    var strArr = str.split("");
    let len = strArr.length;
    for(let i=1; i<=len; i++){
       revArr.push(strArr[len - i]);
    }
    return revArr.join("");
  } 
console.log(reverseString("Greetings from Earth"));

Comments

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.