Obtain eligibility by determining the attribute value of an array object

I am trying to calculate the total qualifications based on a specific attribute value (idInteraction). How can I efficiently iterate through the array?

My current approach is to iterate based on abilityOrder, but I'm having trouble matching it with idInteraction.

var arrayQ = [
    '{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":40}',
    '{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":2, "qualification":60}', 
    '{"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":20}', 
    '{"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":2, "qualification":30}'
];

var q = 0;

function findMinMax(arr) {
    let min = JSON.parse(arr[0]).abilityOrder,
        max = JSON.parse(arr[0]).abilityOrder;
    for (let i = 1, len = arr.length; i < len; i++) {
        let v = JSON.parse(arr[i]).abilityOrder;
        min = (v < min) ? v : min;
        max = (v > max) ? v : max;
    }
    return [min, max];
}

var maxAbility = findMinMax(arrayQ);

arrayQ.forEach(function(result, index) {
    result = JSON.parse(result);

    if (result.abilityOrder >= maxAbility[0] && result.idInteraction) {
        q += result.qualification;
        console.log('id: ' + result.idInteraction + ', q: ' + q);
        q = 0;
    }
});

The expected output should be:

"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}" - q = 100
"idInteraction":"{8ae8653e-99ef-11e9-9e08-90c283d38b9a}" - q = 50

Does anyone have any suggestions or improvements?

Thank you in advance.

Answer №1

To calculate the sum based on the idInteraction value, you can make use of the reduce function:

const data = ['{"idInteraction":"{9ae8653e-99ef-11e9-9e08-90c283d38b9a}","abilityOrder":1, "qualification":40}', '{"idInteraction":"{9ae8653e-99ef-11e-2019-9e08-90c283d38b9a}","abilityOrder":2, "qualification":60}', '{"idInteraction":"{8ae8653e-99ef-11e-9e08-90c283d38b9a}","abilityOrder":1, "qualification":20}', '{"idInteraction":"{8ae8653e-99ef-11e-9e08-90c283d38b9a}","abilityOrder":2, "qualification":30}'];

const result = data.map(item => JSON.parse(item))
    .reduce((acc, current) => acc.set(current.idInteraction, ~~acc.get(current.idInteraction) + current.qualification), new Map);

console.log(result); // Check the console for output as Maps are not directly shown in SO.
console.log(Array.from(result));

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

Use Protractor to simulate Loss Connection by clearing LocalStorage in a Spec

Currently, I am utilizing the code window.localStorage.removeItem("name of localStorage variable you want to remove"); to eliminate two distinct localStorage Keys within a particular specification, and it is successfully removing them. Afterwards, I proce ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Apache Cordova NFC reader integration is the next step in modern technology

I am trying to utilize phonegap nfc ( PhoneGap tutorial ) to read NFC cards, but the event is not being triggered. Here is the code from index.js: onDeviceReady: function() { app.receivedEvent('deviceready'); // Read NDEF formatted NFC T ...

What is the best way to show a message of success once the user has been redirected to the homepage?

Currently, I have a registration form utilizing AJAX and PHP for validation. Error messages can be displayed on the registration page if the user does not correctly fill out the form. Upon successful registration, the user is redirected back to the home pa ...

What makes Next.js API so special?

As I delve into Next.js, I find myself grappling with the concept of server-side rendering (SSR) and API usage. When is it appropriate to utilize the API folder within pages versus deploying my own server along with a database? Would there be any conflic ...

Bringing in an SVG file as a React component

When importing an SVG into React as a Component, I am facing an issue where the CSS classes are wrapped in style tags, causing an error upon import. Removing the CSS from the style tags allows the SVG to load, but it loses its additional styling. I want t ...

Print out the value of the element in the array using the console

Hey there! I have this array that I retrieved from MongoDB and I'm trying to figure out how to console log the value of item. Any tips or suggestions would be greatly appreciated! { "_id" : "61462a7bf3c0be993bcfdc3e", "item&qu ...

Transforming a sequence of numerical values into an array in Java, with each number occupying a distinct position

If I have a string consisting of the numbers 123456789, how can I separate each digit and store them in different slots of an array without using the split() method in Java? ...

Ways to display information using a show/close button in React

I am currently immersed in the learning process of React. My goal is to display information about different countries using a toggleable button. However, I have encountered some obstacles along the way. There's an input field that triggers upon enteri ...

Changing the order of elements in a JavaScript array

Issue: Develop a function that accepts an array as input and outputs a new array where the first and last elements are switched. The initial array will always be at least 2 elements long (for example, [1,5,10,-2] should result in [-2,5,10,1]). Here is ...

What type of JSON format is most suitable for a complex, multi-dimensional array?

Looking for advice on how to convert an excel table into a json structure. Any recommendations on the best way to do this? https://i.sstatic.net/gRshl.png ...

Struggling to properly parse JSON data using jQuery

I am a beginner in jquery and have a php script that returns JSON data. However, I am facing an issue while trying to fetch and process the result using jquery. Below is the code snippet: calculate: function(me, answer, res_id, soulmates) { conso ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

The React higher order component does not pass props to the HTML element

Looking for a way to add a custom background to any component simply by passing it through a function. This method works well with components created using React.createElement, but unfortunately does not work with standard HTML components. const Title = ...

Preserving the status of altered DOM elements across different pages

Hey there, I've successfully created a vertical menu with jQuery slideUp and slideDown functionalities. The menu is working smoothly, but now I'm looking for a solution to keep its state after a postback. For example, if a user clicks a button c ...

Handling right-click events with jQuery live('click')

There has been an interesting observation regarding the functionality of the live() function in jQuery: <a href="#" id="normal">normal</a> <a href="#" id="live">live</a> $('#normal').click(clickHandler); $('#live&ap ...

I am having trouble saving my map data into the MySQL database using PHP

Hi, I'm encountering an issue where data is not being stored in the table I created in my MySQL database. Initially, with only two tables named trip and route, the data was populating correctly. However, now that I've added more tables (Droute, W ...

Obtaining the file size on the client side using JSF RichFaces file upload

I am currently using version 4.3.2 of rich fileupload in JSF richfaces. The issue I am facing is that the files first get uploaded to the server and then an error is thrown if the file size exceeds a certain limit. Even though I have set a size restriction ...

What is the most effective way to eliminate error messages from the email format checker code?

Recently, I've been working on a code to validate forms using javascript/jquery. One particular issue I encountered was related to checking email format. The problem arose when entering an invalid email - the error message would display correctly. How ...

Uninitialized Variable in C Multiple Dimensions Array

I am attempting to create a basic 2D array to store student grades, but I keep encountering an error message stating "variable not initialized". #include <stdio.h> int main() { int const rows = 3; int const columns = 4; int studentsGr ...