Retrieve every item from a collection

Here's what I've got:

objArray1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}];

objArray2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }];

I'm using Javascript to create an array with all the candidates and display the number of votes each one has. Calculating the votes is simple, but combining all the candidates into one array is where I need help.

The final array should include: Alex, Paul, Ben, and Melisa.

Your assistance would be greatly appreciated!

Answer №1

To efficiently group data by name, consider using a hashtable.

var array1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}],
    array2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }],
    grouped = [array1, array2].reduce(function (hash) {
        return function (r, a) {
            a.forEach(function (o, i) {
                var name = o['candidate' + (i + 1)];
                if (!hash[name]) {
                    hash[name] = { candidate: name, votes: 0 };
                    r.push(hash[name]);
                }
                hash[name].votes += o.votes;
            });
            return r;
        };
    }(Object.create(null)), []);
    
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

let contestants = [];
let tally = 0;
for(let x=0;objArray2.length>x;x++){
    tally = 0;
    //include votes in contestant array
    for(let y=0;contestants.length>y;y++){
        if(contestants[y].title==objArray2[x][Object.keys(objArray2[x])[0]]){
           contestants[y].points = contestants[y].points+objArray2[x].points;
           tally = 1;
        }
    }
    //if contender not present in toting array, create new one
    if(tally==0){
         let temp = {};
         temp.title = objArray2[x].title;
         temp.points = objArray2[x].points;
         //append to the array
         contestants.push(temp);
    }
}

console.log(contestants);

Answer №3

Develop a function that creates an object with the candidate name as the key and their total vote count as the value.

var objArray1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}], objArray2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }];

var result = []
  // combine two arrays
  .concat(objArray1, objArray2)
  // iterate over the arrays
  .reduce(function(object, item) {
    // get the key excluding votes
    var key = Object.keys(item).find(function(k) {
      return k !== 'votes';
    })
    // define property if not already defined
    object[key] = object[key] || 0;
    // add the vote count
    object[key] += item.votes;
    // return object reference
    return object;
    // set initial value as empty object
  }, {});

console.log(result);
// get the names array if needed
console.log(Object.keys(result));

Answer №4

Here is a concise solution that utilizes Array.prototype.concat(), Array.prototype.reduce(), and Array.prototype.map() functions:

var candidatesSet1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}],
    candidatesSet2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }],
    
    groupedCandidates = candidatesSet1.concat(candidatesSet2).reduce(function(result, object){
        var key = Object.keys(object).filter(function(key){
                return key.indexOf('candidate') === 0; 
            })[0];

        (result[object[key]])? result[object[key]].votes += object.votes : result[object[key]] = {candidate: object[key], votes: object.votes};
        return result;
    }, {}),

    finalResult = Object.keys(groupedCandidates).map(function(k){ return groupedCandidates[k]; });
    
console.log(finalResult);

Answer №5

To obtain the requested list of names

let combinedArrays = objArray1.concat(objArray2);
let CandidatesList = [];
let temp = [];

for (let i in combinedArrays) {
    temp[combinedArrays[i][Object.keys(combinedArrays[i])[0]]] = 1;
}
CandidatesList = Object.keys(temp);

To generate an array with candidates and total votes

let combinedArrays = objArray1.concat(objArray2);
let CandidatesList = [];

for (let i in combinedArrays) {
    let name = combinedArrays[i][Object.keys(combinedArrays[i])[0]];
    if (CandidatesList[name]) {
        CandidatesList[name] += combinedArrays[i].votes;
    } else {
        CandidatesList[name] = combinedArrays[i].votes;
    }
}

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

Using the jqLite .html() method directly as a watch listener in AngularJS

I'm attempting to use the jqLite function element.html directly as a listener for a watcher: angular.module('testApp', []).directive('test', function () { return { restrict: 'A', link: function (scope, element, ...

Toggle a MutationObserver using a button to stop and start monitoring for changes

Is there a way to connect a MutationObserver and disconnect it using the same button? I know how to do each separately, but I want to use just one button. How can I achieve this? Apologies for my poor English. var target = document.getElementsByClassNa ...

PHP is failing to insert the JSON stringified data into MySQL as an array

I am struggling with inserting data into a database from a JSON.stringify format. Here is the code snippet: $('#get-checked-data').on('click', function(event) { event.preventDefault(); var checkedItems = []; $("#check-list ...

Alert: Prop type error encountered - The prop 'open' must be defined in Snackbar component

Recently, I've been implementing jest snapshot tests into my application. The main focus is on the LoginForm component. render() { return ( ... <DynamicSnack dialogOpen={this.props.dialogOpen} snackOpen={this.props.sna ...

Issue with firestore IN query when encountering NULL value

Is there a way to create a query that retrieves all documents without a value, whether it be null or ''? Within my table are three documents, each containing a field called a. https://i.sstatic.net/FGV0Z.png During an IN query, the document wit ...

Creating a flexible image layout within a container with relative positioning

I attempted to create a basic slideshow with images sliding from right to left as an animation: let slides = document.querySelectorAll('.img-container'); let l = slides.length; let i = 0; setInterval(function(){ i = (i + 1) % l; if(i == 0){ f ...

What is the process to enable a tab in AngularJS using Foundation's tab feature?

Currently, I am utilizing AngularJS in conjunction with Foundations. Visit the official website for more information Within my page, there are two tabs that are functioning correctly as shown below: <tabset> <tab heading="tab1"> </tab ...

Is there a way to determine if an app is installed on a phone using Javascript within Safari on iOS 9 or later?

Prior to iOS 9, one method of determining whether an app was installed on an iPhone using javascript involved utilizing a custom URI scheme followed by a timeout: window.location = "yourapp://"; setTimeout(function() { window.location = "h ...

Currently, my goal is to generate an array of choices using jsView from a data value

When dealing with an array of items lacking properties, how can you extract the value within a for loop? I am able to generate the correct number of options, but I am struggling to find the right syntax to access the option's value. You can view a wo ...

Obtaining the minimum values from various arrays of fields

After utilizing the Google Distance Matrix API, I successfully created this array in PHP. My current objective is to compare the [distance] field within the array, identify the lowest value, and store the corresponding key in a variable. How can I achieve ...

Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS. My Technologies: AngularJS, Angular-UI-router, Bootstrap Key HTML snippet: <select ng-model="selectedCompany" ng-options="c.name for c in companies" ...

The setState function in React updates the value, however, when a form is submitted, it captures and

Encountering a problem with a modified field value not remaining on the form after submission. Working on a form where users can upload images. The image URL returned by the hosting service is saved in a state variable using this.setState({ im ...

Adjusting icons based on the length of the text

When I have a title text and an icon, I want to align the icon to the left if the title fits on a single line. However, if the title spans multiple lines, then I need to align the icon to the top. I recently discovered a solution that involves using Javas ...

"Troubleshooting a CSS problem with off-canvas layouts

I've created a page with divs that create a parallax effect on scrolling, you can view the demo here. However, I encountered an issue when adding a Foundations off-canvas menu - it prevents me from being able to scroll down. How can I resolve this an ...

Unraveling encrypted data from Java in Node.js: a step-by-step guide

Currently, I am working on converting Java lambda functions into JavaScript lambda functions. Specifically, I am focused on converting the encrypt and decrypt methods from Java to Node.js or JavaScript. So far, I have tried implementing this using the &apo ...

Countdown Timer in React Native

Hey, I am new to React Native and JavaScript. I want to create a simple countdown where you can input a number and select the type of countdown - whether it's in seconds, minutes, or hours. For example, if I choose 'seconds' in a dropdown an ...

Utilize jQuery to generate an HTML table from a JSON array with rows (Issue: undefined error)

please add an image description hereI am attempting to populate the data in an HTML table using jQuery, but all columns are showing as undefined errors HTML: <table id="example" class="table table-striped" style="width:100%&quo ...

Obtaining values from a JSON object in JavaScript without the accompanying key

I have an object in JSON format as shown below, and I am looking to extract values from the array without needing to specify a key const myData = { "VALUEX": "GrandTotal", "VALUEX2": "GrandTotal", "Jan-2018": 25, "Feb-2018": 54.5, "Mar-2018": ...

Navigating through asynchronous transactions in Node.js: A Guide

My application utilizes Nodejs, Mongodb, and amqp. The main module receives messages from amqp, processes them by saving message information into mongodb within a message transaction, and executes additional logic. function messageReceiverCallback(msg) { ...

The algorithm for editing multiple phone numbers

I'm working on a form for my project that requires saving 4 phone numbers. The text boxes for entering the phone numbers are revealed on button clicks. Here's what I need to implement: When adding entries---> Enter the first phone number. C ...