# Covert ForLoop to ForEach in Javascript

#### Tags: for-loop, foreach, javascript

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 .
For the equal elements a and b, no points are earned.
Finally, for elements 2, a > b 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++
else if (a[i] < b[i]) scoreboard++
}
return scoreboard
}
compareTriplets(a, b)```

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

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

```function compareTriplets(a, b) {
return [
(a > b) + (a > b) + (a > b),
(a < b) + (a < b) + (a < b)
]
}
```

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