0

I'm trying to use reverse() method to reverse a simple array.
The array is returned from https and I need to reverse the element in it.

console.log("Before Reverse:")
console.log(this.newArr);
this.newArr[0].reverse();
console.log("After Reverse:")
console.log(this.newArr);    

enter image description here

However when I declare an array and use reverse() It can be reversed.:

var arr = [[1,2,3,4],[2,3,4,5],[3,4,5,6]];
arr.reverse();


Please help, thanks!

hatched
  • 795
  • 2
  • 9
  • 34
  • 2
    I believe you need to assign the reversed array to a new variable.. ex: var reversedArray = this.newArr[0].reverse(); then console.log(reversedArray); see what you get – wakakak Nov 25 '19 at 03:39
  • @GlenK Thanks! It works by assigning to another variable. Just not sure why is it ? – hatched Nov 25 '19 at 03:44
  • Are you using the reverse native method? Maybe make the reverse method async in the class with async/await or promises. – Michael Nov 25 '19 at 03:53
  • Array#reverse *transposes the elements of the calling array object **in place***, so assigning to a different variable makes absolutely no difference - the person who suggested that, and the two people that clicked "this comment adds something useful to the post" clearly have no knowledge of javascript - it comes down to what you see in the console - which is explained in the duplicate – Bravo Nov 25 '19 at 03:54
  • @Michael - what? – Bravo Nov 25 '19 at 03:54
  • try changing the two `console.log(this.newArr);` to `console.log(JSON.stringify(this.newArr, null, 4));` - now the console won't trick you – Bravo Nov 25 '19 at 03:55
  • @Bravo by changing the `console.log()` after `reverse()` still doesn't seems to reverse the array – hatched Nov 25 '19 at 04:02
  • have you changed **BOTH** console.log so you can see that it has reversed? – Bravo Nov 25 '19 at 04:49
  • what you are actually seeing is the REVERSED version both times in the console – Bravo Nov 25 '19 at 04:49

0 Answers0