I have two arrays currently
array1 = [5, 10, 20]
array2 = [10, 20, 30]
Either array3 or something like this:
array4 = [{"a":5, "b":10}, {"a":10, "b":20}, {"a":20, "b":30}]
I know this is probably an easy question but I'm not even sure what array3 would be called so its kind of hard to google this.
-
That's not even a valid result.Bergi– Bergi2013年03月21日 19:49:57 +00:00Commented Mar 21, 2013 at 19:49
-
rel: stackoverflow.com/q/4856717/989121georg– georg2013年03月21日 20:26:31 +00:00Commented Mar 21, 2013 at 20:26
3 Answers 3
Very simple, first we create a result array, then we iterate through the first array and add elements to it. Here is a working fiddle.
Note, in your code you have notation like {5,10} which is illegal in JavaScript, I assumed you mean an array.
var result = [];
for(var i=0;i<array1.length;i++){
result.push([array1[i],array2[i]]);
}
Update after edit , it seems like you want objects, try
var result = [];
for(var i=0;i<array1.length;i++){
result.push({a:array1[i],b:array2[i]});//add object literal
}
If you'd like, you can also use map and write the same code functionally. Here is a fiddle of that sort of implementation
Comments
This is called zip...
function zip() {
var args = [].slice.call(arguments);
var shortest = args.length==0 ? [] : args.reduce(function(a,b){
return a.length<b.length ? a : b
});
return shortest.map(function(_,i){
return args.map(function(array){return array[i]})
});
}
Check Underscore a fantastic js library with many of these utility functions...
2 Comments
reduce and map which need to be shimmed first.You can do this easily with a new ES6 feature.
var array1 = [5, 10, 20];
var array2 = [10, 20, 30];
var combineArray = [...array1 , ...array2];
//output should be like this of combine array : [5, 10, 20, 10, 20, 30]
If you want to extra item inside two array then you can do this using below way:
var combineArray = [...array1, 333, ...array2];
//output should be like this of combine array : [5, 10, 20, 333, 10, 20, 30]