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?

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; }

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);

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)

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; }

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.