Merge multiple arrays based on their index using javascript

前端 未结 7 915
清歌不尽
清歌不尽 2020-12-11 16:44

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.

7条回答
  •  失恋的感觉
    2020-12-11 17:13

    You can use a combination of reduce and concat (source):

    var array1 = [1, 2, 3, 4];
    var array2 = ["a", "b", "c", "d"];
    var newArray = array1.reduce(function(prev, curr) {
      return prev.concat(curr, array2[prev.length / 2]);
    }, []);
    $("#result").html(newArray);
    
    

提交回复
热议问题