Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge multiple arrays based on their index using javascript

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>
like image 557
Shabi Levi Avatar asked Apr 02 '17 16:04

Shabi Levi


People also ask

How do I combine multiple arrays into one?

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.

How do you combine two or more arrays in JavaScript?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays.

How do you merge the first index of an array with the first index of second array in JavaScript?

$array1 = array ( "a" , "b" , "c" ); $array2 = array ( "c" , "d" , "e" ); $result = array_merge ( $array1 , $array2 );

How do you merge two arrays using the spread Operator?

To combine two or more arrays, you can either use the functional method []. concat(arr1, arr2) or the spread operator [...arr1,...arr2].


1 Answers

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);
like image 170
Nina Scholz Avatar answered Oct 10 '22 05:10

Nina Scholz