1

I have two arrays that are the same length, for example var a = [5,2,6,2,7,5]; and var b = [2,3,7,4,3];. I also have another array which is var c = [0,0,0,0,0];

How do I compare a and b to put the highest element into c which in this case should become [5,3,7,7,5];

nem035
  • 34,790
  • 6
  • 87
  • 99
  • Possible duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Alan Larimer Oct 22 '17 at 00:57
  • 1
    Your two arrays of the same length are not of the same length. – llama Oct 22 '17 at 01:27

6 Answers6

2

ES6 single-line solution:

c = a.map((a, i) => a > b[i] ? a : b[i])
dhilt
  • 18,707
  • 8
  • 70
  • 85
2

Array#map into a new array, and take the max of the current number from a, and the number with the same index from array b:

const a = [5, 2, 6, 2, 7];
const b = [2, 3, 7, 4, 3];
const c = a.map((num, i) => Math.max(num, b[i]));

console.log(c);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

You would iterate through both arrays, doing the comparison at each step, and inserting the larger number:

Note: Even though you mention that you have equal length arrays, the two sample arrays you've given don't have the same length so my example uses similar equal-length arrays:

let a = [5, 2, 6, 2, 7]
let b = [2, 3, 7, 4, 3]
let c = [0, 0, 0, 0, 0]

// we can use a single loop index `i` since the arrays have same length
for (let i = 0; i < a.length; i++) {

  // take the current number from a and from b
  let numA = a[i]
  let numB = b[i]

  // determine larger of the two numbers
  let largerNumber = numA > numB ? numA : numB

  // add larger to array at current position
  c[i] = largerNumber
}

console.log(c)

You can simplify your solution to be a simple map operation, as demonstrated by dhilt.

nem035
  • 34,790
  • 6
  • 87
  • 99
0

Just use a simple for loop:

var a = [2, 3, 7, 8];
var b = [3, 2, 5, 9];
var c = [0, 0, 0, 0];

for (var i = 0; i < c.length; i++) {
  c[i] = a[i] > b[i] ? a[i] : b[i];
}

console.log("Result: "+c);
Derek Brown
  • 4,232
  • 4
  • 27
  • 44
-1

see example:

var a = [5,2,6,2,7,5];
var b = [2,3,7,4,3];
var c = [0,0,0,0,0];
for(var i in c){
 c[i]=a[i]>b[i]?a[i]:b[i];
}
console.log('result:' + c);
ferhado
  • 2,363
  • 2
  • 12
  • 35
-1

try this, below code takes two arrays and gives the result of max number

var array=[5,3,7,7,5];
var array2 = [5,6,4];
var array3=array.concat(array2);
var max=array3.sort((a,b)=>b-a)[0];
console.log("Result: " + max);