简体   繁体   中英

merge three arrays with same length & get an array of equal length

I have three arrays:

arr1= [1,2,3,4,5];
arr2= [a,b,c,d,e];
arr3= [p,q,r,s,t];

I want to merge these & get another array as shown below:

arr4= [1:a:p, 2:b:q, 3:c:r, 4:d:s, 5:e:t]

Please suggest how can I do it using java script?

Keep in mind that the exact result you are looking for is not possible in JavaScript, you would be getting a string array since you want to have both strings and numbers present within the same element:

var result = ["1:a:p", "2:b:q", "3:c:r", "4:d:s", "5:e:t"];

That said, here's a couple solutions.

You can loop through them and add a concatenation to a result array:

var arr1= [1,2,3,4,5];
var arr2= [a,b,c,d,e];
var arr3= [p,q,r,s,t];

var result = [];

for (var i = 0; i < arr1.length; i++) {
    result.push(arr1[i] + ':' + arr2[i] + ':' + arr3[i])
}

console.log(result);

Or use Array.prototype.map() :

var arr1= [1,2,3,4,5];
var arr2= [a,b,c,d,e];
var arr3= [p,q,r,s,t];

var result = arr1.map(function(val, i) {
    return arr1[i] + ':' + arr2[i] + ':' + arr3[i];
});

console.log(result);

Iterate over the first array with map function and get the index of the items into the passed function. Use the index to access other arrays items and make your desired result. This works if you have the same length for all arrays.

 const arr1= [1,2,3,4,5]; const arr2= ['a','b','c','d','e']; const arr3= ['p','q','r','s','t']; const mappedArray = arr1.map((item, index) => `${item}:${arr2[index]}:${arr3[index]}`); console.log(mappedArray);

You could take all arrays or an arbitrary count of arrays in an array and map the values at the same index.

 var arr1 = [1, 2, 3, 4, 5], arr2 = ['a', 'b', 'c', 'd', 'e'], arr3 = ['p', 'q', 'r', 's', 't'], result = [arr1, arr2, arr3].reduce((a, b) => a.map((c, i) => c + ':' + b[i])); console.log(result);

I'm not sure this is what you want. If so, please search a little bit before asking questions implying simple functions.

var arr1 = [1,2,3,4,5]
var arr2 = ['a','b','c','d','e']
var arr3 = ['p','q','r','s','t']
var arr4 = []
arr1.forEach(function (elm, idx) {
  arr4.push(elm + ':' + arr2[idx] + ':' + arr3[idx])
})

console.log(arr4) // ['1:a:p', '2:b:q', '3:c:r', '4:d:s', '5:e:t']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM