How to compare the data array. I have an array with three subarrays:

var arr = [ [10, 10, 10, 20, 60], [10, 10, 50, 10, 10], [20, 10, 30, 20, 10] ]; 

I need to collect one array, with the maximum values ​​of these three arrays. The length of the arrays is always the same, if in one 5 values, then in the other two the same.

The output should be such an array: var arr = [20, 10, 50, 20, 60]

  • 2
    Can you write loops? Did nested loops go through? Specify what is your problem with the solution of the question. - Kromster
  • and what output should be for the provided example? - Grundy
  • The output should be such an array: var arr = [20, 10, 50, 20, 60] - Vgfva gdf dfh
  • Add this to the question itself. You can edit the question using the edit button questionable - Grundy
  • Π΄ΠΎΠ»ΠΆΠ΅Π½ получится Π²ΠΎΡ‚ Ρ‚Π°ΠΊΠΎΠΉ массив: var arr = [20, 10, 50, 20, 60] - how it fits into the concept: МнС Π½ΡƒΠΆΠ½ΠΎ ΡΠΎΠ±Ρ€Π°Ρ‚ΡŒ ΠΎΠ΄ΠΈΠ½ массив, с ΠΌΠ°ΠΊΡΠΈΠΌΠ°Π»ΡŒΠ½Ρ‹ΠΌΠΈ значСниями этих Ρ‚Ρ€Π΅Ρ… массивов. ? - Alexey Shimansky

2 answers 2

 const arr = [ [10, 10, 10, 20, 60], [10, 10, 50, 10, 10], [20, 10, 30, 20, 10] ]; const arrLength = arr.length; const subArrLength = arr[0].length; const flattenArr = [].concat(...arr); const result = []; for (let i = 0; i < subArrLength; i++) { const indexes = []; for (let j = 0; j < arrLength; j++) { indexes.push(flattenArr[i + j * subArrLength]); } result.push(Math.max(...indexes)); } console.log(result); // [20, 10, 50, 20, 60]; 

  • why is flattenArr needed? why not use arr[i][j] ? - Grundy
  • I recommend using the @Grundy variant with reduce . Declarative> Imperative. - YozhEzhi

The simplest solution is to run through one of the internal arrays and compare the current element with the values ​​at the same index in the neighboring arrays and select the maximum one.

You can implement using the map method , for example:

 function* nextMax(arr, index) { // ΠΏΠΎΠ»ΡƒΡ‡Π°Π΅ΠΌ массив ΡΠΎΠΎΡ‚Π²Π΅Ρ‚ΡΡ‚Π²ΡƒΡŽΡ‰ΠΈΠΉ ΠΊΠΎΠ»ΠΎΠ½ΠΊΠ΅ index for (var i = 0; i < arr.length; i++) { yield arr[i][index]; } } var arr = [ [10, 10, 10, 20, 60], [10, 10, 50, 10, 10], [20, 10, 30, 20, 10] ]; var dest = arr[0].map((cur, i) => Math.max(...(nextMax(arr, i)))); console.log(dest); 


An alternative solution would be to use the reduce method with a gradual comparison:

 var arr = [ [10, 10, 10, 20, 60], [10, 10, 50, 10, 10], [20, 10, 30, 20, 10] ]; var dest = arr.reduce((acc, cur) => acc.map((el, i) => Math.max(el, cur[i])) ) console.log(dest); 

  • The output array with an array. - YozhEzhi
  • @YozhEzhi, corrected - Grundy