1

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

1
  • In my opinion it's not a generic JS question, because when you're talking about React state, you usually don't want to mutate your data. That's why using a simple this.state.lists.unshift(result) is not the best thing you can do even though it works to some extent. Commented Dec 27, 2016 at 9:26

1 Answer 1

4

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],
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.