Exploring the wonders of array filtering and reducing in Javascript

Can someone help me turn an array of voter objects into a count of how many people voted? I'm just starting to learn JavaScript and feeling confused with the reduce and filter methods. When I run the code, I get undefined @@

    function totalVotes(arr) {
    let result = arr.filter(function(vote){
   return vote.voted === true;
 }).reduce(function(total, current){
   return total + 1;
 },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}
];``

Answer №1

If you're looking for the most efficient method, simply filter and tally

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

Answer №2

To calculate the total number of voters who have voted, you can use a single reduce function and add the boolean value of the object to the count.

function calculateTotalVoters(array) {
    return array.reduce(function(count, voter) {
        return count + (voter.voted ? 1 : 0);
    }, 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(calculateTotalVoters(voters));

Answer №3

Let's tackle the issue with this approach:

let qualifiedVoters = voters.reduce((previous, current, index, array) => {
    if (current.voted === true && current.age >= 18) {
        previous.push(current);
    }
    return previous.length;
}, {});
console.log(qualifiedVoters);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locate the indices of several maximum values within an array

Here is an array for reference: var exampleArray = [10, 67, 100, 100]; The goal is to identify the indexes of the maximum values in the array. The existing function currently locates only one index: function findMaxIndexes(arr) { var max = arr[0] ...

The request header fails to function properly when used for cross-domain Ajax requests

I'm facing a challenge with adding a parameter in the request header. It works smoothly for calls within the same domain, but when making a call to a different domain (the API), I need to adjust the header parameter itself. Here is the snippet of cod ...

Having trouble connecting and establishing an onmousemove event?

I am looking to implement a mouse move event handler in my three.js project, but I have been struggling to connect it with the mouse and make it work. It would be greatly appreciated if someone could provide guidance on how to achieve this. I am not sure ...

Looking to expand the width of the sub menu to reach the full width of the

Is there a way to use CSS to make a sub-menu start from the left side of the screen instead of starting it below the parent item? nav { margin: 0 auto; text-align: center; } nav ul ul { display: none; } nav ul li:hover > ul { di ...

Utilizing modal functionality for seamless integration of new data into mui-datatable

When trying to add a new data entry using a modal box, I encountered an issue where the new data was not being added to the datatable. Is there a solution for this problem? Below is the code snippet I used: let id = 0; function createData(name, provider) ...

Is it feasible to implement different themes besides 'light' and 'dark' in React Material UI?

Currently, I am developing a user interface (UI) using React in combination with Material UI (v5+). The documentation provides information on how to utilize the extendTheme function along with CssVarsProvider to incorporate MUI colors into CSS. It also men ...

Add information to an array by simply modifying the existing data that shares the same key/value pair

Currently, I am working on the front-end of a delivery web application. On one of the screens, I have implemented a Google map that allows the company owner to track their delivery riders in real-time. The process of implementing the map itself was quite s ...

Creating two arrays of coordinates to represent concentric squares involves first defining the coordinates of the squares

I am aiming to generate two sets of coordinates representing two regions containing concentric squares or circles (I have only experimented with squares so far, but initially intended to work on simple concentric circles). To clarify, in order to obtain a ...

Creating a 3D element using JSON data in combination of Three.js and React.js

Let me explain the situation as best as I can. I am currently working on a React.js application and learning as I go. I am in the process of incorporating a 3D element into my page, specifically a sofa, that users can interact with using their mouse to mov ...

What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files. Below is a snippet of the JavaScri ...

How can I troubleshoot the 'mdDialog console error' that says 'cannot read property element of null'?

Two of my templates are named Left_template_view_html and center_template_view_html When I click on a md-button in the Left_template_view_html I am attempting to display an mdDialog on the document.body What should I pass into the parent parameter: angu ...

Verification of a Basic Form

I am currently in the process of learning JavaScript. My current goal is to figure out how to loop through an entire form and identify any errors that need to be pointed out. The code I have put together is a mix of different tutorials that I found online ...

Is it possible to utilize global variables within CSS properties?

I have a scenario where I need to dynamically change values in an animation. The line of code that needs modification is: clip-path: polygon(var(clip1) 0, 100% 1%, 100% 100%, 50% 100%); let root = document.documentElement; root.style.setProperty('c ...

Why am I receiving a null response from my ajax request?

I have a working ajax call to fetch XML data from my REST API. However, when I try to echo the results, JQuery returns null. If I use var_dump on the results instead, JQuery accepts the information but it's not formatted correctly and causes errors. ...

Deliver the event target within the data-bind click HTML

I am having trouble sending the event target when passing parameters in data-bind. <button class="tablinks" data-bind="click:$root.notify.bind(this, 1, 'foo');" id="defaultOpen">PRINCIPAL</button> self.notify = function (str, id, e) ...

Calculate the sum of values in a JSON array with JMESPath

Currently, I am encountering some difficulties while attempting to utilize the `sum` function within `JMESPath`. Despite this, I was able to successfully navigate the search function with multiple conditions. The following statement: let x = search(myData ...

What is the proper way to initialize a function that interacts with the redux state?

Imagine a scenario where I have a function that retrieves a filepath from the state based on the filename provided as an input parameter. If the filepath does not exist in the state, it then fetches the filepath from a server URL. const getFilepath = (stat ...

The ajax function does not provide a response

Can you help me figure out why this JavaScript function keeps returning 'undefined'? I really need it to return either true or false. I've included my code below: function Ajax() { var XML; if(window.XMLHttpRequest) XML=new ...

Google Scripts: Generating a set of data to include in an email

As a newcomer to Google Script and JavaScript, I'm on a mission to email a list of file names extracted from a spreadsheet. The names reside in a column within my sheet, and after defining a variable called "newfiles" to cherry-pick only the necessary ...

Finding the following index value of an object within a foreach loop

In my code, I have an object called rates.rates: { AUD="1.4553", BGN="1.9558", BRL="3.5256"} And I am using the following $.each loop: $.each( rates.rates, function( index, value ){ console.log(index); }); I have been attempting to also log the n ...