4
var newlist = list.slice( 0, pos ).concat( tasks ).concat( list.slice( pos ) );

This makes me shudder just looking at it.

Hamster
  • 557
  • 2
  • 7
  • 12
  • it doesn't look that bad to me. It might be a little faster to just scoot the tail of the array out and drop in the new element, however. If you have to do this a *lot* you might want to think about a better data structure anyway. – Pointy Sep 03 '10 at 19:17
  • You mean a tree of some kind? What would you recommend? – Hamster Sep 03 '10 at 19:30

3 Answers3

2

There is a splice method for Array.

Jacob
  • 77,566
  • 24
  • 149
  • 228
  • But that appears to need each parameter listed out. How do I unfurl another array to be that function's extended parameters, then? Or DOES it accept an array parameter to splice together (as opposed to splicing the passed array as only a single item in the new array)? – Hamster Sep 03 '10 at 19:09
  • Yikes, that is ugly. You could use the `apply` method of the `splice` function and build the parameter array from the array you want to splice in, but that's exceptionally hideous. I'm thinking you're better off with your version. – Jacob Sep 03 '10 at 19:32
1

If you didn't want to modify the original array, you can shorten yours a little like this:

var newlist = ​list.slice(0,pos).concat(tasks,list.slice(pos));

http://jsfiddle.net/RgYPw/

user113716
  • 318,772
  • 63
  • 451
  • 440
  • It looks like you are trying to insert an array in the middle of another array. You can use the function `insertArrayAt()` in this answer http://stackoverflow.com/a/12189963/984780. You would use it like this `insertArrayAt(list, pos, tasks)`. This alters `list` if you want a new list use `slice(0)` to clone the list first. Like so: `var newlist = insertArrayAt(list.slice(0), pos, tasks)` – Luis Perez Aug 31 '12 at 15:01
0

Your method is as good as any- you'd have to splice each member of your second array individually.

var list=[1,2,3,4,5,6,7,8,9], tasks= ['a','b','c'], pos=3;


while(tasks.length ) list.splice(pos,0,tasks.pop());

alert(list.join('\n'))

/*  returned value:
1
2
3
a
b
c
4
5
6
7
8
9
*/
kennebec
  • 102,654
  • 32
  • 106
  • 127