Covert ForLoop to ForEach in Javascript

Tags: , ,



I was practicing in Hackerrank JavaScript problems. I found one test which is called Compare the triplets. This is the problem:

a = [1, 2, 3]
b = [3, 2, 1]
 For elements *0*, Bob is awarded a point because a[0] .
 For the equal elements a[1] and b[1], no points are earned.
 Finally, for elements 2, a[2] > b[2] so Alice receives a point.
 The return array is [1, 1] with Alice's score first and Bob's second.
 

I found the solution like this:

let a = [17, 28, 30];
let b = [99, 16, 8];
function compareTriplets(a, b) {
  let scoreboard = [0, 0];
  for (let i = 0; i < a.length; i++) {
    if (a[i] > b[i]) scoreboard[0]++
    else if (a[i] < b[i]) scoreboard[1]++
  }
  return scoreboard
}
compareTriplets(a, b)

I wanted to convert the ForLoop into ForEach method. But I could not find the way to do that.

Answer

This ain’t what you asked for, but let me show you something:

function compareTriplets(a, b) {
  return [
    (a[0] > b[0]) + (a[1] > b[1]) + (a[2] > b[2]),
    (a[0] < b[0]) + (a[1] < b[1]) + (a[2] < b[2])
  ]
}

or, less noise:

function compareTriplets([a, b, c], [d, e, f]) {
  return [
    (a > d) + (b > e) + (c > f),
    (a < d) + (b < e) + (c < f)
  ]
}

simpler, faster and also shorter.

I mean, it’s literally called “compare triplets”. There ain’t any dynamic length or something; and the loop is short. You can easily unroll the loop.

let a = [17, 28, 30];
let b = [99, 16, 8];

function compareTriplets([a, b, c], [d, e, f]) {
  return [
    (a > d) + (b > e) + (c > f),
    (a < d) + (b < e) + (c < f)
  ]
}

console.log(compareTriplets(a, b));


Source: stackoverflow