1

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?

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.