jQuery - merge two arrays with alteration
Im trying to find simplest way to merge two arrays into the third one, with jQuery, like this:
[A,B,C,D]
[1,2,3,4]
The answer would be:
[A,1,B,2,C,3,D,4]
Another e开发者_开发知识库xample:
[A,B,C] + [1,2,3,4,5] = [A,1,B,2,C,3,4,5]
[A,B,C,D] + [1,2,3] = [A,1,B,2,C,3,D]
var result = [];
var a = ['A','B','C','D'];
var b = [1,2,3,4];
$.each(a, function (index, value) {
result.push(value);
result.push(b[index]);
});
Try it here: http://jsfiddle.net/GcTx7/3/
Without jQuery:
for (var i = 0, l = a.length; i < l; ++i) {
result.push(a[i], b[i]);
}
This one takes care of the case when the two arrays do not have the same length:
for (var i = 0, l = Math.max(a.length, b.length); i < l; ++i) {
if (i < a.length) result.push(a[i]);
if (i < b.length) result.push(b[i]);
}
http://jsfiddle.net/GcTx7/1/
You can directly create an Array using the jQuery.map()
[docs] method. When you return an Array, jQuery.map
does a .concat()
.
This will also prevent holes in the Array when lengths differ.
http://jsfiddle.net/zbCj7/
var chars = ['A','B','C','D'];
var nums = [1,2,3,4];
var res = $.map( chars.length > nums.length ? chars : nums, function(v,i) {
var chr = chars[i];
var num = nums[i];
if( chr !== undefined && num !== undefined ) {
return [chr,num];
} else if( chr === undefined ) {
return num;
} else {
return chr;
}
});
or a little more concise:
http://jsfiddle.net/zbCj7/1/
var chars = ['A','B','C','D'];
var nums = [1,2];
var res = $.map( chars.length > nums.length ? chars : nums, function(v,i) {
var chr = chars[i];
var num = nums[i];
return ( chr !== undefined && num !== undefined ) ?
[chr,num] : ( chr === undefined ) ? num : chr;
});
If you really want to make it concise, you could do this:
http://jsfiddle.net/zbCj7/2/
var chars = ['A','B','C','D'];
var nums = [1,2];
var res = $.map( chars.length > nums.length ? chars : nums, function(v,i) {
return [ chars[i], nums[i] ].slice( chars[i]===undefined,
nums[i]===undefined || 2 );
});
Another way to do that using jquery is :
var a = [1,2,3,4];
var b = ['a','b','c'];
var merged_array = mergeArray([a,b]);
function mergeArrays(arrayOfArray) {
var result = [];
for (var i = 0; i < arrayOfArray.length;i++ ) {
$.merge(result, arrayOfArray[i]);
}
return result;
}
This way you can merge as many arrays u want without worrying about the size of individual array.
Hope this helps out as well.
精彩评论