0

Turn an array of voter objects into a count of how many people voted Please help me i starting learn javascript but i'm so confused with reduce and filter some one can fix ? I run code and undefined @@``

    function total(arr) {
    let result = arr.filter(function(votes){
   return votes !==true;
 }).reduce(function(item,cur){
   return [(+item),+(+cur)];
 },[0]);}
var voters = [
  {name:'Bob' , age: 30, voted: true},
  {name:'Jake' , age: 32, voted: true},
  {name:'Kate' , age: 25, voted: false},
  {name:'Sam' , age: 20, voted: false},
  {name:'Phil' , age: 21, voted: true},
  {name:'Ed' , age:55, voted:true},
  {name:'Tami' , age: 54, voted:true},
  {name:'Mary', age: 31, voted: false},
  {name:'Becky', age: 43, voted: false},
  {name:'Joey', age: 41, voted: true},
  {name:'Jeff', age: 30, voted: true},
  {name:'Zack', age: 19, voted: false}
];``
2
  • 2
    voters.filter(x=>x.voted).length Commented Oct 7, 2019 at 22:07
  • thanks everyone i just do it :D Commented Oct 8, 2019 at 17:43

3 Answers 3

1

the best and shortest way to do it, just filter and count

let voters = [
  {name:'Bob' , age: 30, voted: true},
  {name:'Jake' , age: 32, voted: true},
  {name:'Kate' , age: 25, voted: false},
  {name:'Sam' , age: 20, voted: false},
  {name:'Phil' , age: 21, voted: true},
  {name:'Ed' , age:55, voted:true},
  {name:'Tami' , age: 54, voted:true},
  {name:'Mary', age: 31, voted: false},
  {name:'Becky', age: 43, voted: false},
  {name:'Joey', age: 41, voted: true},
  {name:'Jeff', age: 30, voted: true},
  {name:'Zack', age: 19, voted: false}
];

voters.filter(person => person.voted).length
Sign up to request clarification or add additional context in comments.

Comments

0

You could take a single reduce and add simply the boolean value of the object to the count.

function total(array) {
    return array.reduce(function(count, voter) {
        return count + voter.voted;
    }, 0);
}

var voters = [{ name: 'Bob', age: 30, voted: true }, { name: 'Jake', age: 32, voted: true }, { name: 'Kate', age: 25, voted: false }, { name: 'Sam', age: 20, voted: false }, { name: 'Phil', age: 21, voted: true }, { name: 'Ed', age:55, voted: true }, { name: 'Tami', age: 54, voted: true }, { name: 'Mary', age: 31, voted: false }, { name: 'Becky', age: 43, voted: false }, { name: 'Joey', age: 41, voted: true }, { name: 'Jeff', age: 30, voted: true }, { name: 'Zack', age: 19, voted: false }];

console.log(total(voters));

Comments

-1

Here is one way you could solve the problem:

console.log(voters.reduce((prev,curr,i,ar)=>{
    (curr.voted==true && curr.age >=18) ?  ans.push(curr) : null
    return ans.length
},{}))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.