Merge multiple arrays based on their index using javascript

前端 未结 7 913
清歌不尽
清歌不尽 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 Array#map in plain javascript.

    var array1 = [1, 2, 3, 4];
    var array2 = ["a", "b", "c", "d"];
    
    var newArray = array1.map((e, i) => e + array2[i]);
    console.log(newArray);

    If you use map on array1 then first parameter is current value of array1 in loop and the second parameter is index of that element in array. So you can match current element in array1 with elements from other arrays with the same index using index.

    var array1 = [1, 2, 3, 4];
    var array2 = ["a", "b", "c", "d"];
    var array3 = ["f", "d", "s", "a"];
    
    var newArray = array1.map(function(value, index) {
      return value + array2[index] + array3[index];
    });
    console.log(newArray);

    0 讨论(0)
  • 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);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="result"></div>

    0 讨论(0)
  • 2020-12-11 17:17

    Just a little variation note, to merge by index in an array multiple, to create an associative array of values.

    const a = [1, 2, 3, 4],
          b = [34, 54, 54, 43]
    
    console.log(
      a.map((e,i) => [e,b[i]])
    )


    Then later, to search for the closest match from a given value. On this example, searching for the best associated value for 3.7:

    const a = [1, 2, 3, 4],
          b = [34, 54, 54, 43],
          c = a.map((e,i) => [e,b[i]]),
          search = 3.7,
          temp = [];
          
    c.forEach(function(e){
      temp.push(e[0])
    })
    
    const seek = temp.reduce((m, n) => (Math.abs(n-search) < Math.abs(m-search) ? n : m))
    
    const index = c.findIndex((s) => s.indexOf(seek) !== -1)
    console.log(c[index][1])

    This is obviously how behave an object, but it's very useful to me in many special cases.

    For example, identical index entries aren't merged but are holding their associated values in a new entry, we can roll math from the index, and create transformation matrix. We can use any column as index and search both way.

    In computer science, an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.

    Operations associated with this data type allow:

    the addition of a pair to the collection
    the removal of a pair from the collection
    the modification of an existing pair
    the lookup of a value associated with a particular key
    

    https://en.wikipedia.org/wiki/Associative_array

    0 讨论(0)
  • 2020-12-11 17:22

    In case someone needs to merge any number of arrays (with fixed length) in the way mentioned above in the post, following function will be useful

    console.clear();
    var array1 = ["a1", "b1", "c1", "d1"];
    var array2 = ["a2", "b2", "c2", "d2"];
    var array3 = ["a3", "b3", "c3", "d3"];
    var array4 = ["a4", "b4", "c4", "d4"];
    
    function mergeElementsAtIndex(one_or_more_arrays){
        const total_arr = arguments.length;
        newArray = arguments[0].map((v, k) => {
      	var temp_val = v;
            for(var i=1; i < total_arr; i++){
        	    temp_val += arguments[i][k];
            }
            return temp_val;
        });
        return newArray;
    }
    merged_array = mergeElementsAtIndex(array1, array2, array3, array4);
    console.log(merged_array);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    0 讨论(0)
  • 2020-12-11 17:22
    var array1 = [1, 2, 3, 4];
    var array2 = ["a", "b", "c", "d"];
    var array3 = ["f", "d", "s", "a"];
    
    var newArray = array1.map(function(value, index) {
      return value + array2[index] + array3[index];
    });
    console.log(newArray);
    
    0 讨论(0)
  • 2020-12-11 17:33

    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);

    0 讨论(0)
提交回复
热议问题