Home > Back-end >  How to best merge arrays?
How to best merge arrays?

Time:10-21

I have 3 arrays. I need to add some values from array "data2" and "data3" to "array1". I wrote a code example, but in my code, I missing all indexes that do not exist in the "data1" array:

  • index 3 from the "data2" array
  • indexes 3,4,5 from the "data3" array

Of course, I can run over each array separately and compare it to "data1" and insert all, but this is not so "good" solution. What would be a better solution?

const data1 = [
    {name:'aa', value: 1},
    {name:'bb', value: 33},
]

const data2 = [
    {name:'aa', value: 11, type:'test1'},
    {name:'bb', value: 22, type:'test2'},
    {name:'cc', value: 55, type:'test3'}
]

const data3 = [
    {name:'aa', value: 100},
    {name:'bb', value: 200},
    {name:'cc', value: 300},
    {name:'dd', value: 300},
    {name:'ee', value: 300}
];

for(let index in data1){
    let indexData2 = data2.findIndex((row => row.name == data1[index].name))
    if(indexData2 > -1){
        data1[index].value  = data2[indexData2].value;
        data1[index].type = data2[indexData2].type;
    }
    let indexData3 = data3.findIndex((row => row.name == data1[index].name));
    if(indexData3 > -1){
        data1[index].value  = data3[indexData3].value;
    }
}

console.log('data1: ', data1);

CodePudding user response:

You are using data1 as reference, but it will never match the indexes it does not have.

const data1 = [
    {name:'aa', value: 1},
    {name:'bb', value: 33},
]

const data2 = [
    {name:'aa', value: 11, type:'test1'},
    {name:'bb', value: 22, type:'test2'},
    {name:'cc', value: 55, type:'test3'}
]

const data3 = [
    {name:'aa', value: 100},
    {name:'bb', value: 200},
    {name:'cc', value: 300},
    {name:'dd', value: 300},
    {name:'ee', value: 300}
]

const indexes = {}
const allData = [data1, data2, data3]

for (const group of allData) {
  for (const entry of group) {
    const name = entry.name

    indexes[name] = indexes[name] || {}
    
    indexes[name].name = entry.name
    indexes[name].type = indexes[name].type || entry.type
    indexes[name].value = (indexes[name].value || 0)   entry.value
  }
}

const data = Object.values(indexes)

console.log(data)

  • Related