Reputation: 905
I have a list of arrays with me. Here it is
array1= [ab,bc];
array2= [12,23];
array3= [vw,wx];
Now i need to make an object of array like the one mentioned below from the above list
[ab,12, vw] as 1st array
[bc,23,wx] as 2nd array
And these two arrays should now be in a single object. how can i achieve this ?
Upvotes: 0
Views: 81
Reputation: 2058
try something like this:
array1= ['ab','bc',33];
array2= [12,23,35];
array3= ['vw','wx',34,'hh'];
array4= ['vw1','wx1',36];
//object
var mixarrays = {
minmax:'min',//decide col max or min
decide_size:function(arrs){
var size = this.minmax=='max'? 0 :999999;
for(i in arrs){
if(arrs[i].length > size && this.minmax=='max'){
size = arrs[i].length;
}else if(arrs[i].length < size && this.minmax=='min'){
size = arrs[i].length;
}
}
return size;
},
init:function(arrs){
cols = this.decide_size(arrs);
var mixedarray = [];
for(var i=0;i<cols;i++){
mixedarray[i] = [];
for(j in arrs){
mixedarray[i].push(arrs[j][i]);
}
}
return mixedarray;
}
};
//[array1,array2,array3,array4];//array of arrays
console.log(mixarrays.init([array1,array2,array3,array4]));
Upvotes: 2
Reputation: 14658
Check this out. This is more dynamic implementation with no hard-coding of assumptions.
function prepareObjectOfArrays(myArrays){
var myObj = [];
var maxArrLength = calculateMaxLength(myArrays);
for(var i=0; i<maxArrLength; i++){
var tempArr = [];
for(var j=0; j<myArrays.length; j++){
tempArr.push(myArrays[j][i]);
}
myObj.push(tempArr);
}
console.log(myObj);
}
function calculateMaxLength(myArrays){
var maxLength = 0;
for(var j=0; j<myArrays.length; j++){
var tempLength = myArrays[j].length;
if(maxLength < tempLength){
maxLength = tempLength;
}
}
return maxLength;
}
Now invoke as below:
var array1= ['ab','bc'];
var array2= [12,23];
var array3= ['vw','wx'];
prepareObjectOfArrays([array1, array2, array3]);
As I said, this is more dynamic implementation with no hard-coding of assumptions, and will even work with more type of inputs. There could be more corner cases but this is almost fully dynamic. Check with below inputs:
var array1= ['ab','bc','de', 'er'];
var array2= [12,23,34];
var array3= ['vw','wx','yz'];
var array1= ['ab','bc','de', 'er'];
var array2= [12,23,34,45,56,78];
var array3= ['vw','wx','yz'];
Upvotes: 1
Reputation: 3333
You can use zip
function from lodash
library.
_.zip([ab, bc], [12, 23], [vw, wx]);
// -> [[ab, 12, vw], [bc, 23, wx]]
Upvotes: 2