1

I have two arrays. The first array contains some values while the second array contains some elements which should be inserted to the first array. For example:

var aArr = [ {'a':111}, {'b':222}, {'c':333} ... ]
var bArr = [ {'x': 0}, {'y': 0} ] // I'm not sure it's length 

// finail I need got something like 
var aArr = [{'x': 0}, {'y': 0}, {'c':333} ...]

and bArr array is not sure it's length ,maybe it has one element

var aArr = [ {'a':111}, {'b':222}, {'c':333} ... ]
var bArr = [ {'x': 0} ] 

// finail I need got something like 
var aArr = [{'x': 0}, {'b': 222}, {'c':333} ...]

I use splice() which not work very well

var a = [1, 2, 3],
    b = [4, 5];

function prependArray(a, b) {

    a.splice(0, b.length, b);
    return a;
}

var result = prependArray(a, b);
// result =  [[4, 5], 3]  not  [ 4, 5, 3]

What should I do? ? I need more efficient method, because the aArr have more than 3000 values, and bArr have more than 100 values.

thanks.

4
  • How about a = b.concat(a);? Or, if you can use ES 5, then a.splice(0, 0, ...b);? Commented Nov 17, 2014 at 8:14
  • @TheParamagneticCroissant: Excellent point, but doing the wrong thing (OP could have been clearer with description, but that's neither here not there). With ES5, a.splice(0, b.length, ...b) should do it. Commented Nov 17, 2014 at 8:24
  • 1
    @Amadan yap, I realized that too late, too bad I can't edit my comment after 5 minutes... Commented Nov 17, 2014 at 8:24
  • 1
    Define "more efficient". Do you mean fewest lines of code, fastest performance regardless of how much code? Or something else? Commented Nov 17, 2014 at 9:02

6 Answers 6

4

There are many ways to do this, but not as many that preserve the original aArr reference (e.g. modify the actual aArr array without creating a new one). Here's one way:

aArr.splice(0, bArr.length);            // remove front-most bArr.length items from aArr
aArr.unshift.apply(aArr, bArr);         // insert bArr items in front of aArr

This removes the first bArr.length items form aArr and then adds the bArr items to the front of aArr, all the while preserving the original aArr reference (e.g. not replacing it with a new array).


It can also be done in one .splice(), but that requires building a temporary array to pass to .splice.apply() which didn't seem worth it since that makes an entirely new array just to save one line of code. In any case, that would look like this:

aArr.splice.apply(aArr, [0, bArr.length].concat(bArr));

If you really want max "efficiency" in terms of performance rather than in terms of lines of code, then you will probably need to do performance benchmarks using a tool like jsperf and test in multiple browsers. It may be that simply copying over the bArr items into aArr is the most "efficient" because that has the fewest array manipulations. To know for sure, you would have to measure actual performance at your typical array sizes across several browsers.

For pure performance, you should test this vs the options above:

for (var i = 0, len = bArr.length; i < len; i++) {
    aArr[i] = bArr[i];
}

This has the advantage that it does not create any temporary arrays and does not have to shift the items in aArr around. It has the disadvantage of running the loop in plain javascript, not in native array manipulation code.


It appears that the last option of just copying elements over is 7x faster in Chrome, 10x faster in IE11 and even more of a difference in Firefox.

See the jsperf here: http://jsperf.com/array-shift-vs-copy

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

Added jsperf reference.
whet is jsperf reference? where did you get it?
@Manwal - I created a jsperf performance test and linked to it in my answer.
The jsperf compares the performance of two methods of accomplishing the task. You can see the code for the two methods in the jsperf itself.
1
function prependArray(a, b) {
    return a.splice.apply(a, [0, b.length].concat(b))
}

Thanks The Paramagnetic Croissant (*_*)

Comments

0

There is a concat-Method in Javascript:

result = b.concat(a);

Edit: forgot to remove the old values in a:

After the concat, apply splice:

result.splice(b.length, b.length);

Working example: http://jsfiddle.net/9sLjnu66/

2 Comments

tanaydin, you win this time :)
This makes a new array - it doesn't preserve the original aArr reference. I'm not 100% sure that is required, but it looks like the OP shows aArr getting modified, not a new array getting created.
0

var aArr = [{
  'a': 111
}, {
  'b': 222
}, {
  'c': 333
}]
var bArr = [{
    'x': 0
  }, {
    'y': 0
  }] // I'm not sure it's length 

for (var i = 0; i < bArr.length; i++) {
  if (i > aArr.length) break;
  aArr[i] = bArr[i];
}

//show the results
document.write(JSON.stringify(aArr));
The result should be:
<br>
<code>
  [{'x': 0}, {'y': 0}, {'c':333}]
</code>
<br>And it is:
<br>

Comments

0

Another idea is

bArr.concat(aArr.slice(bArr.length))

In other words, slice off the first n elements of the first array, where n is the length of the second array, then append that to the second array.

Comments

0

In ECMAScript 6:

a.splice(0, b.length, ...b);

8 Comments

Whats the ...b mean?
Perhaps you mean ECMAScript 6?
@torazaburo is it just ES6? I thought it was in ES 5 already.
@jfriend00 it's parameter unpacking. If b is an array, then ...b expands to an argument list containing the elements of b.
You confused the heck out of me by originally claiming ES5.
|

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.