I need to merge two arrays into a single array. I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>
<body>
<div id="result"></div>
<script type="text/javascript">
var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var newArray = $.merge(array1, array2);
$("#result").html(newArray);
//the result its 1234absd
//ineed result like 1a,2b,3c,4d
</script>
</body>
</html>
Using the spread operator or the concat() method is the most optimal solution. If you are sure that all inputs to merge are arrays, use spread operator . In case you are unsure, use the concat() method. You can use the push() method to merge arrays when you want to change one of the input arrays to merge.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays.
$array1 = array ( "a" , "b" , "c" ); $array2 = array ( "c" , "d" , "e" ); $result = array_merge ( $array1 , $array2 );
To combine two or more arrays, you can either use the functional method []. concat(arr1, arr2) or the spread operator [...arr1,...arr2].
You could use Array#reduce
and Array#map
for an arbitrary count of arrays with same length.
var a1 = [1, 2, 3, 4],
a2 = ["a", "b", "c", "d"],
a3 = [9, 8, 7, 6],
a4 = ["z", "y", "x", "w"],
result = [a1, a2, a3, a4].reduce((a, b) => a.map((v, i) => v + b[i]));
console.log(result);
ES5
var a1 = [1, 2, 3, 4],
a2 = ["a", "b", "c", "d"],
a3 = [9, 8, 7, 6],
a4 = ["z", "y", "x", "w"],
result = [a1, a2, a3, a4].reduce(function (a, b) {
return a.map(function (v, i) {
return v + b[i];
});
});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With