Reputation: 83
I'm a beginner so I apologize for the "easy" question. Thank you.
let majority = (arr, call) => {
let reducedArr = arr.reduce(function(accu, item, index) {
if (call(item) >= index) {
return true
} else {
return false
}
})
}
const isOdd = function(num) {
return num % 2 === 1;
};
console.log(majority([1, 2, 3, 4, 5], isOdd)); // should log: true
console.log(majority([2, 3, 4, 5], isOdd)); // should log: false
Upvotes: 0
Views: 344
Reputation: 216
You just need to return return reducedArr;
for that piece of code to work how ever i don't think that your logic is correct since you are resetting your accumulator for each element in the array. if you can edit and add what you are trying to accomplish may be we can help you more.
after seeing what you are trying to accomplish here is a snippet with some comments that my help you understand it better i know reduce can be tricky when you are learning it but you will get the hang of it.
let majority = (arr, call) => {
let reducedArr = arr.reduce(function( acc, item ) {
// call(item) returns true if number is odd so there is no need to check it against index
if ( call(item) ) {
// if number is odd we increase the odd count in the accumulator
acc.odd +=1
} else {
// if number is even we increase the even count in the accumulator
acc.even+=1
}
return acc;
}, {odd: 0, even: 0}) //initial accumulator value
return reducedArr.odd > reducedArr.even; // return true if odd count is larger than even count
}
const isOdd = function(num) {
return num % 2 === 1;
};
console.log(majority([1, 2, 3, 4, 5], isOdd)); // should log: true
console.log(majority([2, 3, 4, 5], isOdd)); // should log: false
hope this help.
Upvotes: 1
Reputation: 782498
majority()
needs to return something. Since it doesn't have a return
statement, it returns undefined
by default.
Your reduce()
logic is all wrong, since it's not using the accumulator parameter.
From the name and your expected results, I assume that the function is supposed to return whether the call
function is true for the majority of elements in the array. So you can use reduce
to count the number of true results, by adding 1
to accu
whenever it's true. Then you return accu
to update the accumulator as it's iterating through the array.
You also need to supply the initial value of the accumulator as the second argument to reduce()
. Otherwise, it uses the first element of the arr as the initial value.
Then you need additional code to check if this is the majority. Compare this total to half the length of the array.
let majority = (arr, call) => {
let reducedArr = arr.reduce(function(accu, item, index) {
if (call(item)) {
accu++;
}
return accu;
}, 0);
return reducedArr > arr.length/2;
}
const isOdd = function(num) {
return num % 2 === 1;
};
console.log(majority([1, 2, 3, 4, 5], isOdd)); // should log: true
console.log(majority([2, 3, 4, 5], isOdd)); // should log: false
Upvotes: 4