Reputation: 141
I have 3 arrays and want to merge them into one array using the key
first array:
dataStringold = $(this).data("old_position");
result: ["addpr_0", "addpr_1", "addpr_2"]
Second array:
dataStringnew = $(this).data("new_position");
result: ["addpr_0", "addpr_2", "addpr_1"]
Third array:
var values = [];
$('.destino').each(function(){
values.push( $(this).val());
});
result: ["1", "27", "2"]
and all what i need to get eack key of them and merge in new array like that:
["addpr_0","addpr_0","1"] ["addpr_1","addpr_2","27"] ["addpr_2","addpr_1","2"]
how can do it?
Upvotes: 1
Views: 54
Reputation: 386570
You could use an array for an arbitrary count of arrays for getting a transposed array.
var array0 = ["addpr_0", "addpr_1", "addpr_2"],
array1 = ["addpr_0", "addpr_2", "addpr_1"],
array2 = ["1", "27", "2"],
arrays = [array0, array1, array2],
result = arrays.reduce((r, a) => a.map((v, i) => (r[i] || []).concat(v)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 8088
You can go over the first array through for in
and use the index
to access each element.
const arr1 = ["addpr_0", "addpr_1", "addpr_2"]
const arr2 = ["addpr_0", "addpr_2", "addpr_1"]
const arr3 = ["1", "27", "2"]
const result = []
for (let index in arr1)
result.push([arr1[index], arr2[index], arr3[index]])
console.log(result)
Upvotes: 1
Reputation: 1569
If the size of all the array is same, the below code works
var result = ["addpr_0", "addpr_1", "addpr_2"];
var result2 = ["addpr_0", "addpr_2", "addpr_1"];
var result3 = ["1", "27", "2"];
var newResutl =[];
var i =0;
newResutl=result.map(function(item){
var n = result.indexOf(item);
return[item, result2[n], result3[n]];
});
console.log(newResutl);
Upvotes: 1
Reputation: 33726
An alternative is using the function Array.from
and get each element using the index from the handler.
let arr = ["addpr_0", "addpr_1", "addpr_2"],
arr2 = ["addpr_0", "addpr_2", "addpr_1"],
arr3 = ["1", "27", "2"],
result = Array.from({length: Math.max(arr.length, arr2.length, arr3.length)}, (_, i) => [arr[i], arr2[i], arr3[i]]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2