I was practicing in Hackerrank JavaScript problems. I found one test which is called Compare the triplets
. This is the problem:
JavaScript
x
8
1
a = [1, 2, 3]
2
b = [3, 2, 1]
3
For elements *0*, Bob is awarded a point because a[0] .
4
For the equal elements a[1] and b[1], no points are earned.
5
Finally, for elements 2, a[2] > b[2] so Alice receives a point.
6
The return array is [1, 1] with Alice's score first and Bob's second.
7
8
I found the solution like this:
JavaScript
1
11
11
1
let a = [17, 28, 30];
2
let b = [99, 16, 8];
3
function compareTriplets(a, b) {
4
let scoreboard = [0, 0];
5
for (let i = 0; i < a.length; i++) {
6
if (a[i] > b[i]) scoreboard[0]++
7
else if (a[i] < b[i]) scoreboard[1]++
8
}
9
return scoreboard
10
}
11
compareTriplets(a, b)
I wanted to convert the ForLoop into ForEach
method. But I could not find the way to do that.
Advertisement
Answer
JavaScript
1
12
12
1
let a = [17, 28, 30];
2
let b = [99, 16, 8];
3
function compareTriplets(a, b) {
4
let scoreboard = [0, 0];
5
a.forEach((element, i) => {
6
if (element > b[i]) scoreboard[0]++
7
else if (element < b[i]) scoreboard[1]++
8
});
9
return scoreboard
10
}
11
compareTriplets(a, b)
12