8

I'm trying to prepend data to an array in VueJs:

number: [

],

this.number.push({
    number: 1
})

How do I prepend rather than append?

1
  • Push does append to an array... what is the behavior you want? Commented Feb 19, 2016 at 22:08

4 Answers 4

30

Unshift:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

this.number.unshift({number: 1});

You can also pass multiple arguments to add them all:

this.number.unshift({number: 1}, {number: 2});

The return value is the new length of the array:

var foo = [1];
var bar = foo.unshift(2, 3, 4);
//foo = [2, 3, 4, 1]; bar = 4;
Sign up to request clarification or add additional context in comments.

1 Comment

@user3662307 remember: unshift, shift, push and pop
2

Vue wraps an observed only this Array methods: push, pop, shift, unshift, splice, sort, reverse. You can use unshift or splice. For example:

 youArray.splice(0, 0, 'first item in Array');

Comments

0

Unshift is the good solution. But here is a different solution using concat:

this.number = [{number: 1}].concat(this.number);

Comments

0

I would also add the new way of prepending to an array:

this.number = [
 { number: 1 },
  ...this.number
]

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.