Sydney Loteria
Sydney Loteria

Reputation: 10461

Append array at the beginning of the array of objects - Javascript

I'm using react js on this but I think this one is a Vanilla Javascript question. What I want to achieve here is to push an array at the beginning of the lists of objects. current what I have is to append at the end of the object using concat:

this.setState({
            lists: this.state.lists.concat([result])
        });

How can I implement to push at the beginning of the array. This is what the data that will be push at the beginning:

enter image description here

Upvotes: 1

Views: 103

Answers (1)

Tomasz Lenarcik
Tomasz Lenarcik

Reputation: 4880

I think that what you want is probably:

this.setState({
    lists: [result].concat(this.state.lists),
});

But if you're using ES6, there's also a nicer way:

this.setState({
    lists: [result, ...this.state.lists],
});

Upvotes: 4

Related Questions