Reputation: 31
So, I know how to add up the integers in my given array but I am totally stumped on the comparison logic and returning the bool. Recursion or reduce can be used. It doesn't really matter.
This is the last quiz I have to take for my class before I can go on break
function isBalanced(arr1, arr2){
arr1.reduce((a, b) => {
return a + b;
}, 0);
arr2.reduce((a, b) => {
return a + b;
}, 0);
return arr1 === arr2;
}
I'm getting expected false to be true in my tests.
Upvotes: 2
Views: 392
Reputation: 20354
You can do it like this:
let array_1 = [1,2,3,4,5];
let array_2 = [10,5];
const check_if_equal = (arr_1, arr_2)=> arr_1.reduce((a, b) => a + b, 0) === arr_2.reduce((a, b) => a + b, 0);
console.log(check_if_equal(array_1, array_2));
Upvotes: 0
Reputation: 89374
You can use Array#reduce
to find the sum of an array. Then, just compare the sums of the two arrays.
function sum(arr) {
return arr.reduce((a, b) => a + b, 0);
}
function sumEqual(arr1, arr2) {
return sum(arr1) === sum(arr2);
}
console.log(sumEqual([1, 3, 2], [3, 2, 1]));
Upvotes: 1