Array Reverse is not working for me ...
As described at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse, reverse()
reverses the order of an array in place, so the array is reversed after it's been called. You're calling it twice, resulting in the array being restored to its original order. Try this:
poll() {
var self = this;
var url = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40';
$.get(url, function(result) {
result.data.reverse();
console.log(result.data, result);
self.setState({
error: null,
historicalData: result,
isLoading: false
});
}).fail(function(response) {
self.setState({
error: 'Could not fetch average price data. Looks like something went wrong.',
});
}
It has reversed it, the reverse()
is executed before the console.log()
. It mutates the actual array first in place returning a reference so then when it is logged, a
is also reversed.
var a = [1,2,3,4];
console.log(a, a.reverse());
// [4, 3, 2, 1] [4, 3, 2, 1]
Everything inside the console.log
parens is evaluated first. Try 2 reverses, can you guess what happens, it goes back to original order, like in your example.
var a = [1,2,3,4]
console.log(a, a.reverse());
// [4, 3, 2, 1]
The source of your problem is that you don't understand how your browser's console works.
Many browsers have consoles that display objects in the state they are in when you expand them in the console or when you open the console, even if they change after console.log()
is called. So if you do:
console.log(result.data);
result.data.reverse();
console.log(result.data);
you will see the same output twice. The second line reverses the array in place, so both log outputs are showing the same array, in its present state.
To demonstrate this console behavior, you can do the following:
var b = { a: [1, 2, 3] };
console.log(b);
b.a[1] = 9;
console.log(b);
what you will see is that b.a
is [1, 9, 3]
in both console outputs.