Determining the maximum value while omitting a specific value within a property of a nested object

I'm struggling with the specific iteration logic required here. The object structure is somewhat complex:

var answers = {
  cat1: {
    q1: {
      "question": "Why?",
      "answer": "No",
      "points": 6
    },
    q2: {
      "question": "Why oh why?",
      "answer": "50%",
      "points": 15
    },
    q3: {
      "question": "Is it true?",
      "answer": "Maybe",
      "points": 9
    }
  },
  cat2: {
    q1: {
      "question": "Hello?",
      "answer": "Hello",
      "points": 0
    },
    q2: {
      "question": "Why me?",
      "answer": "Because",
      "points": 9
    },
    q3: {
      "question": "Is it true?",
      "answer": "Maybe",
      "points": 0
    }
  },
  cat3: {
    q1: {
      "question": "why not?",
      "answer": "I don't know",
      "points": 15
    },
    q2: {
      "question": "What?",
      "answer": "That",
      "points": 9
    },
    q3: {
      "question": "Is it real?",
      "answer": "Nope",
      "points": 6
    }
  }
}

I need to find the highest points for each category's nested objects, excluding values of 15. Then, I want to add these high scores together.

It seems like using underscore.js could simplify this process by filtering out properties with a value of 15 and then using the _.max() function to determine the highest points for each nested object before summing them up.

For example, in this case, the sum would be 9 + 9 + 9 (27).

If you have any insights or suggestions, I'd greatly appreciate your help!

Answer №1

To calculate the sum of maximum points in each category, you can utilize a straightforward for loop that goes through the keys of your Object. This way, you can gather all the results and add them up accordingly.

var maxPoints = {},
      totalSum = 0;

for (var key in answers) {
    maxPoints[key] = 0;
    for (var item in answers[key]) {
        if (answers[key][item].points != 15) {
            maxPoints[key] = Math.max(maxPoints[key], answers[key][item].points);
        } else {
            delete answers[key][item];
        }
        // ^ Remove the question if it has a score of 15
    }
    totalSum += maxPoints[key];
}

After executing the above code, you can expect a result similar to this:

maxPoints
> {
   category1: 9,
   category2: 9,
   category3: 9
}

totalSUm
> 27

Answer №2

To obtain the highest points by category, you can utilize _.mapObject along with a customized iteratee for _.max:

var maxes = _.mapObject(answers, function (qs) {
    var maxq = _.max(qs, function (q) {
        return (q.points !== 15) ? q.points : -Infinity;
    });

    return maxq.points;
});

The result will be:

{cat1=9, cat2=9, cat3=9}

Demo available at http://jsfiddle.net/v80z9w2y/

To calculate the total using _.reduce:

var sum = _.reduce(maxes, function(memo, num){ return memo + num; }, 0);

Check out the updated demo here: http://jsfiddle.net/v80z9w2y/1/

If only interested in the total sum, both steps can be combined as shown below:

var sum = _.reduce(answers, function (memo, qs) {
    var maxq = _.max(qs, function(q) {
        return (q.points !== 15) ? q.points : -Infinity;
    });

    return memo + maxq.points;
}, 0);

For a demonstration of this combined approach, visit http://jsfiddle.net/v80z9w2y/2/

Answer №3

Check out this alternative approach utilizing underscore:

    let totalSum = _.reduce(answers, function(result, category){
        return result + _.max(_.without(_.pluck(category, 'points'), 15));
    }, 0);

Answer №4

This snippet is designed to be compatible with all modern web browsers and does not require any external libraries

let categories = [];
for (const cat in responses) {
  categories.push(responses[cat]);
}
let total = categories.map(function (cat) {
  let highestPoint = 0;
  for (const q in cat) {
    let question = cat[q];
    if (question.points !== 15) {
      highestPoint = Math.max(highestPoint, question.points);
    }
  }
  return highestPoint;
}).reduce(function (previousValue, currentValue) {
  return previousValue + currentValue;
}, 0);

Answer №5

While the answer may have already been selected, the question itself is intriguing, prompting me to present my own take on it:

function calculateTotalPoints(answers){
    return Object.keys(answers).reduce(function(total, category){
        return total + Math.max.apply(window,
            Object.keys(answers[category]).map(function(question){
                return answers[category][question].points === 15 ? 0 : answers[category][question].points;
            })
        );
    }, 0);
}

Check out my unique implementation on JSFiddle!

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

Troubleshooting problems with AJAX call in custom validation for Knockout JS

I have created a custom validation function that checks whether a zip code entered in a form field is valid for the selected state from a dropdown. The validation works correctly when I initially select a state and then input a zip code, but if I change th ...

Creating a WordPress post popup using Ajax with SimpleModal and jQuery

I tried to follow the instructions provided in this tutorial but unfortunately, I couldn't get it to work. This is the process I followed: 1 / Including in the header <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ...

Implementing a smooth transition effect on an ajax tab

I have a tab code that uses ajax data attributes to load content. The tabs are loaded with ajax from PHP code based on the data attribute. How can I add a fade in/out effect to the tabs' content? I've attempted it but haven't been successful ...

How to access elements in every document fragment

I am facing an issue with a page that contains multiple document fragments. I need to retrieve all elements from the entire page that match a specific selector, like so. document.querySelectorAll('iframe') However, this does not return elements ...

Unable to automatically calculate JavaScript when the number is not manually typed into the dropdown menu

Calculating A and B vertically from a dropdown combo box has been a challenge. Here is a sample data set: Data A B ---------------------------- 1 | 1 | 0 2 | 0 | 1 3 | 0 | 1 ---- ...

How does handleChange receive the value as an input?

Greetings! Currently, I am delving into the world of React and JavaScript. I am experimenting with a Table Component demo that can be found at the following link: https://codesandbox.io/s/hier2?file=/demo.js:5301-5317 In the demo, there is a function defi ...

Is there a way to automatically refresh a webpage in HTML that encounters an error?

I am facing a strange issue. There is a php script that runs exclusively on our webserver, processing a large amount of data immediately after a new job is added to the database. The processing typically takes around 1-5 minutes. To monitor for unfinished ...

Different ways to activate the system bell in Node.js

Currently, I have a custom nodejs script running for an extended period and I'm seeking a way to receive a notification once the script finishes its execution. Is there a method in nodejs that can be used to activate the "System Bell" alert? ...

Is it possible for the handler to still be executed even after canceling an AJAX request?

After exploring the discussion on whether JavaScript is truly single-threaded, it is evident that despite JavaScript being primarily single-threaded, there are exceptions to keep in mind. I am curious about the predictability of the following pseudo-code ...

Is it possible to generate an HTML file without MathML by rendering MathJax/MathML at compilation/preprocessing time?

I am looking for a solution to convert webpages with heavy MathJax (or MathML) usage into ebooks for display on my Kindle, which does not fully support JavaScript or MathML. I am interested in preprocessing the .html files by running MathJax during a com ...

Injecting sinon js into an application within an iFrame: a step-by-step guide

I am looking to implement ajax requests testing in my application. The application is running within an iframe, and my goal is to have the iframe's wrapper page test the application using sinon (which will send the response). I attempted to include ...

Utilize focusout and onclick events on multiple components at the same time

Currently, I am in the process of coding an Autocomplete feature from scratch in Vue, but I am encountering a challenge when it comes to selecting an option from the dropdown menu. I have set it up so that the dropdown is shown when the input is clicked ...

javascript method to apply styling

I'm puzzled by how these two javascript/css codes can yield different results: 1st: prev.setAttribute('style', 'position:absolute;left:-70px;opacity:0.4;border-radius: 150px;-webkit-border-radius: 150px;-moz-border-radius: 150px;&apos ...

What is the method to generate an array of values using a single attribute in GeoJSON data?

Note: After reviewing some possible solutions mentioned in this thread, I found that .map is the perfect fit for what I need, which was not covered in the original post. Thomas's response below addresses my specific requirement. In JavaScript, how ca ...

Is the V8 engine programmed to populate the call stack before executing the code, or does it execute the code upon entering a function?

Below is the code I attempted: // **Setting up variables and functions** let number_object = { num: 0 } function doWork(callback) { //Initiates work, expected to complete after 5 seconds console.log("working") setTimeout(() => { ...

What is the best way to fill in a property for a mongoose schema?

let newPost = new Post({ content: fields.content, creator: req.user, }); newPost.save(function(error) { if(error) { res.status(501).json({ error: error }); } else { res.json({ post: newPost }); } }); The post model has a field called cr ...

Formatting date and time in Google Chart

I am trying to utilize the Google Chart API to create a line chart. I need to retrieve data through an AJAX method and then set this data to the chart using a JavaScript JSON array. However, I am encountering difficulties with the datetime format within th ...

Exploring advanced routing concepts in Angular 2

I have a challenge in setting up routing in angular 2 with the following scenario home.component: @RouteConfig([ { path: '/', name: 'Home', component: HomeComponent }, { ...

The div element remains visible even after performing Page_ClientValidate

I'm facing an issue where the "info" DIV is not being hidden and the "questions" DIV is not being shown when Page_ClientValidate is called and sets isValid to true. Strangely, if I manually set isValid to true or false, it works as expected. Could ...

Uploading pictures to Imgur without the need for an API key

I've been attempting to utilize the imgur API feature that allows you to upload an image by sending a GET request to http://api.imgur.com/2/upload with a URL in the form data. However, I have been unsuccessful in making it work as intended, as it simp ...