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.
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:This removes the first
bArr.length
items formaArr
and then adds thebArr
items to the front ofaArr
, all the while preserving the originalaArr
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: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:
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