Consider the following code (React JS code):
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) {
console.log(result.data, result.data.reverse());
self.setState({
error: null,
historicalData: result.data.reverse(),
isLoading: false
});
}).fail(function(response) {
self.setState({
error: 'Could not fetch average price data. Looks like something went wrong.',
});
});
}
Notice the console.log. Lets see an image:
Last I checked, reverse should have reversed the order of the array. Yet it doesn't.
Am I Using this wrong (official MDN Docs)? Why isn't reverse working?
The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.
Using SwappingInstead, we reverse the original array itself. In this method, we swap the elements of the array. The first element is swapped with the last element. The second element is swapped with the last but one element and so on.
In this method, the idea is to use a negative sign but by storing it into a variable. By using this statement x = (INT_MIN/INT_MAX), we get -1 in a variable x. As INT_MIN and INT_MAX have same values just of opposite signs, so on dividing them it will give -1. Then 'x' can be used in decrementing the index from last.
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]
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.',
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With