Home > Net >  How to loop 3 arrays and merge to 1 array
How to loop 3 arrays and merge to 1 array

Time:02-24

How to loop 3 or more arrays and concatenate them into 1 array. I will omit arrays that have null values, and replace their values with the next array.

  • If the data1 array has a value of null at index 0, it will be replaced with data in the data2 array index 0 which has a value not equal to null.
  • If data2 index0 has value null, then take index0 in array data3.
  • If the array data1 index1 has a value not equal to null, then take the value data1 index1, and discard the values at index1 in data2 and data3

for example

const data1 = ['null', 'Dahak tidak berwarna', 'null', 'null', 'null', 'null', 'null', 'null', 'Terus Menerus', 'null']
const data2 = ['Tinggi', 'Berdahak', 'null', 'null', 'Setelah terbentur', 'Lunak', 'Cair', 'null', 'Tinggi', 'Di Bawah Telinga']
const data4 = ['null', 'null', 'Bagian Dalam', 'null', 'null', 'null', 'null', 'null', 'null', 'Bagian luar']

output

const result = ['tinggi', 'Dahak tidak berwarna', 'Bagian Dalam', 'null', 'Setelah terbentur', 'lunak', 'Cair', 'null', 'Terus Menerus', 'Dibawah Telinga']

how to merger and selection value array

CodePudding user response:

let finalData  = [];    
data1.forEach(function (val, i) {
        finalData.push(val=='null'? ( data2[i]=='null' ? data4[i] : data2[i] ): val)
    });
console.log(finalData);

CodePudding user response:

Your description is not clear i think you are confuse by yourself but this is the result array you asked for i hope this is what your are asking for

const data1 = ['null', 'Dahak tidak berwarna', 'null', 'null', 'null', 'null', 'null', 'null', 'Terus Menerus', 'null'];
const data2 = ['Tinggi', 'Berdahak', 'null', 'null', 'Setelah terbentur', 'Lunak', 'Cair', 'null', 'Tinggi', 'Di Bawah Telinga'];
const data4 = ['null', 'null', 'Bagian Dalam', 'null', 'null', 'null', 'null', 'null', 'null', 'Bagian luar'];

let newArr = [];

for(let i = 0 ; i < data1.length ; i  ){
 newArr[i] = data1[i] != 'null' ? data1[i] : ''   data2[i] != 'null' ? data2[i] : ''   data4[i] != 'null' ? data4[i] : '';
}
console.log(newArr);

CodePudding user response:

Create an array of the input arrays and loop through each them and update the index in the output. Works for any number of input arrays and arrays with different lengths

const data1 = ['null', 'Dahak tidak berwarna', 'null', 'null', 'null', 'null', 'null', 'null', 'Terus Menerus', 'null'],
      data2 = ['Tinggi', 'Berdahak', 'null', 'null', 'Setelah terbentur', 'Lunak', 'Cair', 'null', 'Tinggi', 'Di Bawah Telinga'],
      data4 = ['null', 'null', 'Bagian Dalam', 'null', 'null', 'null', 'null', 'null', 'null', 'Bagian luar'],
      output = [];
      
for (const array of [data1, data2, data4]) {
  for (let i = 0; i < array.length; i  ) {
    if (!output[i] || output[i] === 'null')
      output[i] = array[i]
  }
}

console.log(output)

  • Related