Reputation: 423
given that I want to compare two equally long arrays, if they have the same value at the same position, can I do this with a loop but with NO IF STATEMENT?
This code works
function twoArrays(arr, arr2) {
var count = 0;
arr.forEach (function(item, index){
if(arr[item, index]===arr2[item, index]) {
count++
}
})
return count
}
twoArrays([2,3,4,6],[2,1,4,5])
// return 2
But how about something without an if statement?
EDIT: every time there is a match the counter goes up one. Bonus: can I use other loops? (Which)?
Upvotes: 1
Views: 48
Reputation: 1074465
There are a couple of ways to avoid an if
statement, though it's not clear why you want to.
The first is to use filter
:
var count = arr1.filter(function(item, index) { return item === arr2[index]; }).length;
...but it creates an unnecessary array (temporarily).
Live Example:
function twoArrays(arr1, arr2) {
return arr1.filter(function(item, index) { return item === arr2[index]; }).length;
}
console.log(twoArrays([2,3,4,6],[2,1,4,5]));
The second is to use &&
:
var count = 0;
arr1.forEach(function(item, index) { item === arr2[index] && ++count; });
...but it's really just an if
in disguise. &&
evaluates its left-hand operand and, if that operand is falsy, takes that falsy value as its result (which is then thrown away in the above); if the value of the left-hand operand is truthy, &&
evaluates its right-hand operand and takes that as its result. That means side effects in the right-hand operand only happen if the left-hand operand's value is truthy, which is why ++count
works.
Live Example:
function twoArrays(arr1, arr2) {
var count = 0;
arr1.forEach(function(item, index) { item === arr2[index] && ++count; });
return count;
}
console.log(twoArrays([2,3,4,6],[2,1,4,5]));
Similarly, you could use the conditional operator, either with forEach
:
var count = 0;
arr1.forEach(function(item, index) { count += item === arr2[index] ? 1 : 0; });
...or with reduce
:
var count = arr1.reduce(function(acc, item, index) { return acc + (item === arr2[index] ? 1 : 0); }, 0);
Live Example:
function twoArraysA(arr1, arr2) {
var count = 0;
arr1.forEach(function(item, index) { count += item === arr2[index] ? 1 : 0; });
return count;
}
console.log(twoArraysA([2,3,4,6],[2,1,4,5]));
function twoArraysB(arr1, arr2) {
return arr1.reduce(function(acc, item, index) { return acc + (item === arr2[index] ? 1 : 0); }, 0);
}
console.log(twoArraysB([2,3,4,6],[2,1,4,5]));
...but again, there's still conditional logic in there.
I don't recommend any of them. Just use the if
. :-)
Upvotes: 2