简体   繁体   中英

javascript array unshift some elements

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 (eg 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 (eg 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

在此处输入图片说明

function prependArray(a, b) {
    return a.splice.apply(a, [0, b.length].concat(b))
}

Thanks The Paramagnetic Croissant (*_*)

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/

 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> 

在ECMAScript 6中:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM