Looping through dictionaries in an array with JavaScript for comparison

I am looking to compare a dictionary that contains specific preferences of a coachee with other dictionaries that hold the profiles of coaches.

Each coach will receive a score based on how well they match the coachee's preferences, or be excluded with a score of -1 if they do not meet an important preference.

One coachee will be compared to 24 coaches in order to determine the best match.

QUESTION: How can I efficiently loop through this process?

Below is a sample code:

//coachee\\

var coachee = {
    "gender": 1,
    "age_option_1": 1,
    "age_option_2": 1,
    "age_option_3": 0,
    "topics_option_1": 1,
    "topics_option_2": 0,
    "topics_option_3": 0,
    "industry_option_1": 1,
    "industry_option_2": 0,
    "industry_option_3": 0,
    "experience_option_1": 1,
    "experience_option_2": 0,
    "experience_option_3": 1,
    "language_option_1": 1,
    "language_option_2": 0,
    "language_option_3": 0
}

//coach1\\

var coach1 = {
    coach1_answers_gender : 2,
    coach1_answers_age_option_1 : 0,
    coach1_answers_age_option_2 : 1,
    coach1_answers_age_option_3 : 0,
    coach1_answers_topics_option_1 : 1,
    coach1_answers_topics_option_2 : 0,
    coach1_answers_topics_option_3 : 1,
    coach1_answers_industry_option1 : 1,
    coach1_answers_industry_option2 : 1,
    coach1_answers_industry_option3 : 0,
    coach1_answers_experience_option1 : 1,
    coach1_answers_experience_option2 : 1,
    coach1_answers_experience_option3 : 0,
    coach1_answers_language_option_1 : 1, 
    coach1_answers_language_option_2 : 1,
    coach1_answers_language_option_3 : 1
};

///COMPARISON///

//Topics//

if (answers["topics_option_1"] == 1 && coach1_answers_topics_option_1 == 1) {
    coach1_topics1_score = 1;
} else {
    coach1_topics1_score = 0;
}
if (answers["topics_option_2"] == 1 && coach1_answers_topics_option_2 == 1) {
    coach1_topics2_score = 1;
} else {
    coach1_topics2_score = 0;
}
if (answers["topics_option_3"] == 1 && coach1_answers_topics_option_3 == 1) {
    coach1_topics3_score = 1;
} else {
    coach1_topics3_score = 0;
}

var coach1_topics_score = coach1_topics1_score + coach1_topics2_score + coach1_topics3_score;

//Industry//

if (answers["industry_option_1"] == 1 && coach1_answers_industry_option1 == 1) {
    coach1_industry1_score = 1;
} else {
    coach1_industry1_score = 0;
}
if (answers["industry_option_2"] == 1 && coach1_answers_industry_option2 == 1) {
    coach1_industry2_score = 1;
} else {
    coach1_industry2_score = 0;
}
if (answers["industry_option_3"] == 1 && coach1_answers_industry_option3 == 1) {
    coach1_industry3_score = 1;
} else {
    coach1_industry3_score = 0;
}

var coach1_industry_score = coach1_industry1_score + coach1_industry2_score + coach1_industry3_score;

//Experience//

if (answers["experience_option_1"] == 1 && coach1_answers_experience_option1 == 1) {
    coach1_experience1_score = 1;
} else {
    coach1_experience1_score = 0;
}
if (answers["experience_option_2"] == 1 && coach1_answers_experience_option2 == 1) {
    coach1_experience2_score = 1;
} else {
    coach1_experience2_score = 0;
}
if (answers["experience_option_3"] == 1 && coach1_answers_experience_option3 == 1) {
    coach1_experience3_score = 1;
} else {
    coach1_experience3_score = 0;
}

var coach1_experience_score = coach1_experience1_score + coach1_experience2_score + coach1_experience3_score;

//Total Score//

var coach1_score = (coach1_age_score + coach1_topics_score + coach1_industry_score + coach1_experience_score) * 10;

///EXCLUSION///

//Age//

if (answers["age_option_1"] == 1 && coach1_answers_age_option_1 == 1) {
    coach1_age_score = 1;
} else if (answers["age_option_2"] == 1 && coach1_answers_age_option_2 == 1) {
    coach1_age_score = 1;
} else if (answers["age_option_3"] == 1 && coach1_answers_age_option_3 == 1) {
    coach1_age_score = 1;
} else {
    coach1_score = -1;
}

//Language//

if (answers["language_option_1"] == 1 && coach1_answers_language_option_1 == 1 ) {
  coach1_language_score = 1;
} else if (answers["language_option_2"] == 1 && coach1_answers_language_option_2 == 1 ) {
    coach1_language_score = 1;
} else if (answers["language_option_3"] == 1 ) {
  coach1_language_score = 1;
} else {
  coach1_score = -1;
}

//Gender//

if (answers["gender"] == 3) {
    coach1_gender_score = 1;
} else if (answers["gender"] == coach1_answers_gender) {
    coach1_gender_score = 1;
} else {
    coach1_score = -1;
}

//Repeat for Coach2 and other coaches...

The goal is to have an array of scores such as:

coaches_score = [coach1_score, coach2_score, ...]

Manually repeating the comparison and exclusion blocks for each coach would be time-consuming. Is there a way to efficiently loop through this process? Your insights are greatly appreciated.

Thank you!

Answer №1

I recommend optimizing the data structure by using arrays for a more iterative approach and considering grouping keys for calculating scores.

const
    calculateScore = trainer => {
        const
            score = {},
            keys1 = ['topic', 'industry', 'experience'],
            keys2 = ['age', 'language'];

        keys1.forEach(k => score[k] = trainee[k].reduce((s, v, i) => s + v * trainer[k][i], 0));

        score.totalScore = keys1.reduce((s, k) => s + score[k], 0) * 10;

        keys2.forEach(k => {
            score[k] = +trainee[k].slice(0, -1).some((v, i) => v * trainer[k][i]) || +trainer1[k][trainer[k].length - 1] || 0;
            if (!score[k]) score.totalScore = -1;
        });

        score.gender = +(trainer.gender === 3 || trainee.gender === trainer.gender)
        if (!score.gender) score.totalScore = -1;

        return score;
    },
    trainee = {
        gender: 1,
        age: [1, 1, 0, 0],
        topic: [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1],
        industry: [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0],
        experience: [1, 0, 1, 0, 0],
        language: [1, 0, 0]
    },
    trainer1 = {
        gender: 2,
        age: [0, 1, 0, 1],
        topic: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1],
        industry: [1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1],
        experience: [1, 1, 0, 0, 1],
        language: [1, 1, 1]
    };

console.log(calculateScore(trainer1));

Answer №2

Although the Java Script code seemed too complex for me to fully understand, I managed to make it work by tweaking it a bit. Here's what I changed:

var coach1_values = getScore(coach1)

var coach2_values = getScore(coach2)

var coach3_values = getScore(coach3);

//Adding up the values to calculate the total score\\

const sumValues = obj => Object.values(obj).reduce((a, b) => a + b);

if (coach1_values.score != -1) {
    var coach1_score = sumValues(coach1_values);
} else coach1_score = -1;

if (coach2_values.score != -1) {
    var coach2_score = sumValues(coach2_values);
} else coach2_score = -1;

if (coach3_values.score != -1) {
    var coach3_score = sumValues(coach3_values);
} else coach3_score = -1;

I'm still puzzled as to why the score becomes 110 when it matches the "geschlecht" value, but it doesn't affect the outcome since everyone receives this bonus. Thanks once again for your help!

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

Creating a jQuery-powered assistance pop-up: A step-by-step guide

On various websites, you may have seen a help box labeled with a question mark icon [?], which, when hovered over, displays a small box of additional information. I discovered that these are typically created using a combination of Javascript and jQuery. ...

In the Kendo AngularJS tree view, prevent the default behavior of allowing parent nodes to be checked

Hi there, I am currently using Kendo treeview with Angularjs. My tree view has checkboxes in a hierarchy as shown below Parent1 Child1 Child2 I would like the functionality to work as follows: Scenario 1: if a user selects Parent1 -> Child1, Chil ...

Manipulating a JavaScript object array: Eliminating objects with identical properties. Similar circumstances result in varying outcomes

Attempting to remove an object from an array if the age property matches using the provided codes. var state= [ {name: "Nityanand", age:23}, {name: "Mohit", age:25}, {name: "Nityanand", age:25} ] let a= [ ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

Using an Ember color picker to dynamically change SCSS variables

Is there a way to allow an admin to change the skin of one of my websites by selecting a color from a palette that will update a universal SASS variable? I am aware of methods to dynamically change CSS using jQuery, but I specifically want to modify the S ...

I'm attempting to integrate the map function into my React Redux application, but after implementing useDispatch, I'm encountering an error message in the console

I am currently troubleshooting an app I'm working on, but I keep encountering errors in the console. Included below is a picture of the error as well as the code snippet triggering the issue. Can anyone provide insight into what might be causing this ...

Challenges experienced during the process of uploading a website to the server

I seem to have encountered an issue where the Navigation background image is missing after uploading my website onto the server. Surprisingly, everything else seems to be working perfectly. What could possibly be the cause of this discrepancy? navbar-de ...

Iterate through the classes for updates rather than focusing on individual id fields

I am currently working on creating a function that can refresh data with an AJAX call for multiple instances of a class within a single page. The function functions perfectly when there is only one instance on the page: $(document).ready(function() { ...

Step-by-step guide on how to load an Ext JS tab after clicking on it

I have an Ext JS code block that creates 4 tabs with Javascript: var tabs; $(document).ready( function() { fullscreen: true, renderTo: 'tabs1', width:900, activeTab: 0, frame:true, ...

Is there a way to find a substring that ends precisely at the end of a string?

Looking to rename a file, the name is: Planet.Earth.01.From.Pole.to.Pole.2006.1080p.HDDVD.x264.anoXmous_.mp4 I want to remove everything starting from 2006 onwards. I considered using JavaScript string methods to find the index of the unnecessary part an ...

Utilizing System.import with Webpack 2 and React for splitting code and managing nested routes

I followed the instructions from a tutorial article on Modus Create titled Code Splitting for React Router with ES6 Imports to create an app. I made some modifications by adding children routes, resulting in the following router configuration: function er ...

Including an image in an HTML email template for sending messages

What are your suggestions for displaying the outlook compose box when a button is clicked, with the email body containing an image of a specific DIV? I've been using html2canvas to capture the image and then using mailto to open an Outlook compose mai ...

After the installation of Storybook, there is a duplicate identifier error that arises with 'LibraryManagedAttributes'

Upon running the command npx storybook@latest init for setting up Storybook, which results in modifying package.json, I encounter an issue where I cannot run the project using npm due to: Error: node_modules/@types/react-dom/node_modules/@types/re ...

Dealing with errors: What is the best way to pause and rerun a function after a specified timeout

I am trying to implement a solution for handling asynchronous timeouts by awaiting the execution of a function and then re-executing it with error handling if needed. Here is my pseudo code: 01 call and await async function update() 02 if no error -> c ...

Exploring the Intersection of jQuery and Rails in Dynamic Form Development

I am currently working on an interactive form for a Rails project and need some assistance with listing multiple jQuery functions in the same file. Whenever I try to add a second set of code language, it seems to break the entire file. Below is the Rails ...

How to efficiently search MongoDB for existing records and group them by unique array values

My dataset is structured like this: { "_id" : 1, "category" : [ { "name": "category1" }, { "name": "category2" } ], "event": [ { type: "house" ...

Having difficulty writing to the stream with the stored reference in express-session

For my current project, I have implemented a method to upload large files to the server in manageable chunks of 10MB using the blueimp jQuery-File-Upload plugin. The backend of the application, powered by Node.js, utilizes a writeStream linked to an expres ...

Hidden button trigger is malfunctioning

I am attempting to activate a hidden button, but the event does not seem to be triggering. Here is the code snippet: <div class="dyn-inp-group"> <div class="dyn-inps"> <div class="form-group form-group-options col-xs-12 dyn-inp" ...

What is the best method for saving and retrieving a class object in a web browser's storage?

Looking for a way to create page-reload proof class instances in my Angular 2 application. Within my component's .ts file, I have defined the following classes: export class AComponent implements OnInit { foo: Foo = new Foo(); ngOnInit() { / ...

The issue is that AngularJS deferred.reject function is not functioning properly, while the $q

I'm struggling to understand the difference between Angular JS deferred and $q. I recently came across this SO Question that delves into the variance between $q.defer() and $q. According to the post: $q.reject serves as a quick way to create a defe ...