I know that you can add items to the end of the array with concat
but how do I unshift to add an item to the front?
Add to the end:
var allStatuses = this.state.statusData;
var newStatuses = allStatuses.concat([data.statuses]);
this.setState({statusData: newStatuses});
What I want to do is change the "concat" to something that will put data.statuses to the front and not the end.
Is there a problem doing
[data.statuses].concat(allStatuses);
If you are using ES6, you can do
var newStatuses = [data.statuses, ...allStatuses]
Actually you can use .concat
in this case,
var newStatuses = [data.statuses].concat(allStatuses);
If you want to modify the original array, use Array.unshift
var arr = [1,2,3];
arr.unshift(0);
arr // 0,1,2,3
If you want a new array, use Array.concat as Alexander suggested
this.setState({statusData: [0].concat(this.state.statusData)})
Which is similar to spreading into a new array
this.setState({statusData: [0, ...this.state.statusData]})
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