Merge two arrays by index value by different value in the array [duplicate]

拟墨画扇 提交于 2020-07-10 11:37:09

问题


I have two arrays and I want to merge the values of the two arrays into a single array, but both arrays have different values.

Example:

var arr1 = [
            { data1: 1 ,data2: "value1"},
            { data1: 1 ,data2: "value2"},
            { data1: 2, data2: "value3"},
            { data1: 3 ,data2: "value3"},
            { data1: 3 ,data2: "value3"}
          ];
var arr2 = [
            { data1:1, data3:"val1"}, 
            { data1: 1, data3: "val2"},
            { data1: 2, data3: "val1"},
            { data1: 3, data3: "val1"},
            { data1: 3, data3: "val2"}
           ]; 
var arr3 = [
             { data1:1, data2: "value1", data3:"val1"}, 
             { data1: 1, data2: "value2", data3: "val2"},
             { data1: 2, data2: "value3", data3: "val1"},
             { data1: 3, data2: "value3", data3: "val1" },
             { data1: 3, data2: "value3", data3: "val2" }
           ];

I tried this it, will work fine when data1 is unique, but the problem is when data1 is repeating it merges the first value:

var data = _.map(arr1, function(item){
                return _.extend(item, _.findWhere(arr2, { dataid: item.dataid }));
           });

回答1:


You can use map() and merge the properties of first and second array on same index.

var arr1 = [ { data1: 1 ,data2: "value1"}, { data1: 1 ,data2: "value2"},{ data1: 2, data2: "value3"}, { data1: 3 ,data2: "value3"}, { data1: 3 ,data2: "value3"} ]; 
var arr2 = [ { data1:1, data3:"val1"}, { data1: 1, data3: "val2"}, { data1: 2, data3: "val1"}, { data1: 3, data3: "val1"}, { data1: 3, data3: "val2"} ];

const res = arr1.map((x,i) => ({...x,...arr2[i]}));
console.log(res)


来源:https://stackoverflow.com/questions/56269352/merge-two-arrays-by-index-value-by-different-value-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!