Javascript Data Type How to - Zip two arrays








Question

We would like to know how to zip two arrays.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- www. j a v  a  2s. com-->
var array1 = ["a","b","c"];
var array2 = ["e", "f","g"];
function zip(source1, source2){
    var result=[];
    source1.forEach(function(o,i){
    result.push(o);
    result.push(source2[i]);
    });
    return result
}
document.writeln(zip(array1, array2));

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: