Q: Compare arrays based on higher inner value I have two arrays basically and we need them to compare by checking if the order of elements inner values are both higher on the same column, then count as 1.
I will explain more by showing example
First array
const arr1 = [[1, 3], [6, 5], [4, 2]]

Second array
const arr2 = [[1, 2], [4, 6], [3, 2]]

Based on the above two, we will check the three element of both,
first element - arr1 has [1, 3] and arr2 has [1, 2] and as you can see both of them are higher on second column and it should count.
second element - arr1 has [6, 5] and arr2 has [4, 6] - both are higher on different columns and should not be counted.
third element - arr1 has [4, 2] and arr2 has [3, 2] - both are higher on first column and should be counted as well
and the result of above arrays should be '2 found'.
So far I tried out this, but it outputs 5 instead of 2.


const arr1 = [[1, 3], [6, 5], [4, 2]]
const arr2 = [[1, 2], [4, 6], [3, 2]]

function compare(arr1, arr2) {
  count = 0

  arr1.forEach((e1) => arr2.forEach((e2) => {
    if (e1[0] > e1[1] && e2[0] > e1[1]) {
      count += 1
    } else if (e1[1] > e1[0] && e2[1] > e1[0]) {
      count += 1
    }
  })
  )

  return count

}

result = compare(arr1, arr2)

console.log(result)



A: This is the solution. You were running .forEach twice.


const arr1 = [
  [1, 3],
  [6, 5],
  [4, 2]
];
const arr2 = [
  [1, 2],
  [4, 6],
  [3, 2]
];

function compare(arr1, arr2) {
  let counter = 0;
  arr1.map((value, index) => {
    let foo = arr1[index];
    let bar = arr2[index];
    if ((foo[0] > foo[1] && bar[0] > bar[1] && foo[0] != bar[1]) || (foo[0] < foo[1] && bar[0] < bar[1] && foo[0] != bar[1])) {
      counter += 1;
    }
  })
  return counter;
}

let c = compare(arr1, arr2)
console.log(c);



A: You could make a function that finds that index of the max index of an array. Then just use that to test in a reduce() to count the matches:


// get index of max value in array
const maxIndex = (arr) => arr.reduce((max, curr, i, self) =>  curr > self[max] ? i : max, 0)

const arr1 = [[1, 3], [6, 5], [4, 2]]
const arr2 = [[1, 2], [4, 6], [3, 2]]

let count = arr1.reduce((count, arr, i) => 
    maxIndex(arr) == maxIndex(arr2[i])     // count if the index of the max is the same
        ? count+1 
        : count
    , 0)
console.log(count)



A: A reducer is definitely the way to go.
Keeping along the lines of what you wrote, You just need to do one loop through your one array, and then output that reduction.
const arr1 = [[1, 3], [6, 5], [4, 2]]
const arr2 = [[1, 2], [4, 6], [3, 2]]

const compare = (arr1, arr2) => arr1.reduce((r,o,i) =>
    ((o[0] > o[1] && arr2[i][0] > arr2[i][1]) ||
    (o[0] < o[1] && arr2[i][0] < arr2[i][1])) ? r+1 : r
,0);

result = compare(arr1, arr2)

console.log(result) 

