Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing an object to beginning of an array [duplicate]

Tags:

javascript

I have this array.

var array = [
 {
  title:'Fish'
  id: 1
 },
 {
  title: 'Meat'
  id:2
 }
]

It's used in a drop down. I'd like to add an option at the top:

{
  title:'All'
  id:3
}

How do I push this object to the beginning of the array? If I use push, then it's placed at the end.

like image 780
Joe Avatar asked Jan 25 '26 14:01

Joe


1 Answers

Use the unshift method of the javascript array:

array.unshift({title: 'All', id: 3})
like image 130
Bogdan Iulian Bursuc Avatar answered Jan 28 '26 03:01

Bogdan Iulian Bursuc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!