Toàn Phương
Toàn Phương

Reputation: 1

Javascript array.filter and reduce

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}
];``

Upvotes: 0

Views: 1580

Answers (3)

harith
harith

Reputation: 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
},{}))

Upvotes: -1

Jose
Jose

Reputation: 316

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

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386550

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));

Upvotes: 0

Related Questions