views:

239

answers:

4
+6  Q: 

JavaScript arrays

What is the easiest way to insert a new object into an array of objects at the index position 0? No jQuery; MooTools okay; no unshift() because it's undefined in IE according to w3schools.

+6  A: 

Using splice method.

array.splice(index,howmany,element1,.....,elementX);

For inserting, 'howmany' = 0

o.k.w
`unshift` and `concat` are simpler than `splice` for what @JamesBrownIsDead wants to do.
Dominic Cooney
@Dominic, very true indeed. I guess I'm just 'lazy' to remember different methods and just the more generic ones :P
o.k.w
@o.k.w splice is nice :)
Dominic Cooney
+18  A: 

W3CSchools is really outdated, the unshift method is part of the ECMAScript 3rd Edition standard which was approved and published as of December 1999.

There is no reason to avoid it nowadays, it is supported from IE 5.5 up.

It is safe to use it, even modern libraries like jQuery or MooTools internally use it (you can check the source code :).

var array = [2,3];
array.unshift(1); // returns 3
// modifies array to [1, 2, 3]

This method returns the new array length, and inserts the element passed as argument at the first position of the array.

CMS
-1 Because the OP specifically requested "no `unshift()`"
Darko Z
Guys, there is no reason to avoid `unshift`...
CMS
The questioner specifies no `unshift` because w3schools says it is unsupported in IE. As @CMS points out, that is out-of-date: w3schools doesn't even *track* IE<6 market share any more.
Dominic Cooney
+1 Great answer CMS, as usual :)
Doug Neiner
Alconja
@Alconja: No problem, you can un-down-vote now :)
CMS
@CMS: almost edited your response myself to let me change my vote, but I figured that was a bit rude. :) Anyway, I've switched it to an up-vote now. Well deserved.
Alconja
+5  A: 

You can try this:

var newItem = 3;
arr = [newItem].concat(arr);

Another option is to use push and reverse the indices - you can easily write an object that does that.

Kobi
A: 

I would use unshift() if your intent is to modify the array, otherwise you can use concat() as Kobi suggested (which returns a new array and does not modify the involved arrays):

var arr = [1, 2], newItem = 3;
var newArr = [newItem].concat(arr); // newArr = [1, 2, 3], arr still = [1, 2]

See: concat

kflorence