What is the most effective way to organize and display objects, such as using an "interest" attribute that could be the same for multiple "User" objects?

Hey everyone, I'm facing some challenges while trying to create a function. In the code snippet provided, I aim to develop the interestMatch function. The goal of this function is to analyze all users and identify those who share the same interest - specifically Bob and Jack in my code. I believe an if statement might be useful here. Perhaps something along the lines of: "if any users have the same interest," then "return this user and consider it a match!" Can anyone lend a hand? Thanks a bunch!

class User {
    constructor(username, password, firstname, lastname, email, birthday, gender, interest){
        this.username = username;
        this.password = password;
        this.firstname = firstname;
        this.lastname = lastname;
        this.email = email;
        this.birthday = birthday;
        this.gender = gender;
        this.interest = interest
    }
}
let InterestArray = ["Netflix", "Sports", "Party", "Business", "Children", "Hygge"]

let bob = new User ("bob123", "12345", "Bob", "bobiski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="294b464b694b464b074a4644">[email protected]</a>", "2000-10-10", "male", interest[0]);
let jack = new User ("jack20", "340302", "Jack", "jackiski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e040f0d052e040f0d05400d0103">[email protected]</a>", "2000-06-10", "male", interest[0]);
let thif = new User ("thif20", "204903", "Thifanny", "Thifiski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d1cdccc3e5cfc4c6ce8bc6cac8">[email protected]</a>", "2000-09-12", "female", interest[1]);

function interestMatch(){
???
}

console.log(interestMatch())
// Expected console output: "Bob matches with Jack!" as they share the same interest

Answer №1

One way to approach this problem is by using a nested loop structure where we compare the interests of different users:

function findInterestMatches(users){
  for (let i = 0; i < users.length; i++) {
    const user1 = users[i];
    // We only need to check users that come after user1 to avoid duplicate matches.
    for (let j = i+1; j < users.length; j++) {
      const user2 = users[j];
      if (user1.interest === user2.interest) {
        return `${user1.username} has a matching interest with ${user2.username}`;
      }
    }
  }
}

If users have multiple interests or you are looking to find all matches, it may be helpful to create a map that groups users based on their interests.

Answer №2

It seems that the approach requested by the OP involves a level of complexity beyond just using an if statement

The solution might involve utilizing an if statement in some form.

An effective strategy would be to iterate through a user list, examine each user's interest, and categorize users based on their interests. This establishes a foundational structure known as an interest based map or index containing lists of users associated with specific interests.

This initial step lays down the groundwork for a data structure that can be further manipulated.

Once the necessary data structure is established (a key-value store where interest serves as the key and a corresponding list of users represents each key's value), one can move on to the next phase which involves output presentation.

For every key-value pair (interest and user list), a dedicated rendering function is triggered. During this process, the user list is transformed into a list consisting of individual first names.

The final rendering function must account for potential edge cases such as scenarios where there is only one user with a unique interest or situations where multiple users share a common interest.

class User {
  constructor(
    username, password, firstname, lastname,
    email, birthday, gender, interest
  ) {
    Object.assign(this, {
      username, password, firstname, lastname,
      email, birthday, gender, interest
    });
  }
}

function groupUserByInterest(index, user) {
  const { interest } = user;
  const sameInterestList = index[interest] || (index[interest] = []);

  sameInterestList.push(user);
  return index;
}

const interestList = ["Netflix", "Sports", "Party", "Business", "Children", "Hygge"];

const userList = [
  new User ("bob123", "12345", "Bob", "bobiski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fe9c919cbe9c919cd09d9193">[email protected]</a>", "2000-10-10", "male", interestList[0]),
  new User ("jack20", "340302", "Jack", "jackiski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e882898b83a882898b83c68b8785">[email protected]</a>", "2000-06-10", "male", interestList[0]),
  new User ("jane20", "340303", "Jane", "janinski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b212a252e0b212a252e65282426">[email protected]</a>", "2000-06-10", "famale", interestList[0]),
  new User ("thif20", "204903", "Thifanny", "Thifiski", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="34405c5d52745e55575f1a575b59">[email protected]</a>", "2000-09-12", "famale", interestList[1])
];

// const [ bob, jack, jane, thif ] = userList;

function renderUsersOfSameInterest(interest, userList) {
  const [ first, ...rest ] = userList;
  let template;
  if (!rest.length) {

    template = `There is no other user who matches ${ first }'s interest (${ interest }).`;
  } else {
    template = `${ first }'s interest (${ interest }) maches with the one of ${ rest.join(' and ') }!`;
  }
  console.log(template);
}
function renderUsersOfSameInterestsByFirstname(index) {
  Object.entries(index).forEach(([interest, userList]) =>
    renderUsersOfSameInterest(interest, userList.map(user =>
      user.firstname))
  );
  // console.log('index', index);
}

renderUsersOfSameInterestsByFirstname(
  userList.reduce(groupUserByInterest, {})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

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 React to implement MUI autocomplete feature alongside a MUI form

Recently, I have been utilizing a MUI form structured in the following manner: <Box component="form" onSubmit={event => { return handleSubmit(event); }} noValidate sx={{mt: 1}}> <TextField margin="normal" ...

The data-src tags are functioning properly in the index.html file, but they are not working correctly in angular

I'm still learning about Angular and JavaScript, so please bear with me if my questions seem silly. I've been trying to add a theme to my Angular project. When I include the entire code in index.html, everything works fine. However, when I move ...

What steps should I take to ensure that the proper link is loaded and opened when the loop is clicked?

I've been working on a script to display the top 25 posts from reddit and have their respective links open in a sliding div below. However, I'm running into an issue where the script outputs the same post for every item in the loop. I understand ...

Tips for preserving the status of a sidebar

As I work on developing my first web application, I am faced with a navigation challenge involving two menu options: Navbar Sidebar When using the navbar to navigate within my application, I tend to hide the sidebar. However, every ti ...

The smooth transition of my collapsible item is compromised when closing, causing the bottom border to abruptly jump to the top

Recently, I implemented a collapsible feature using React and it's functioning well. However, one issue I encountered is that when the collapsible div closes, it doesn't smoothly collapse with the border bottom moving up as smoothly as it opens. ...

Does the html label prevent propagation from occurring?

Can anyone explain why the toggle function is not being executed when clicking inside the box with the black border, but works when clicking outside of it (although not on the checkbox)? var checks = document.querySelectorAll("ul li"); for (var i = 0 ...

Triggering a new window on button click with Vue and Nuxt

Having an issue with a button click event in Vue that opens a PDF using window.open(). It's working well on all browsers except for Safari on MAC. Any ideas what could be causing this? Should I pass $event to the method? <div class="button-do ...

I can't believe this ReactJs project generated this code automatically

What does this automatically generated code do in my ReactJs app and what are the advantages of including it? <div class="nsc-panel nsc-panel-compact nsc-hide"> <div class="nsc-panel-move"></div> <div class=" ...

Vue allows a child component to share a method with its parent component

Which approach do you believe is more effective among the options below? [ 1 ] Opting to utilize $emit for exposing methods from child components to parent components $emit('updateAPI', exposeAPI({ childMethod: this.childMethod })) OR [ 2 ] ...

Creating a VSCode extension using Vue: Step-by-step guide

I'm looking to develop a VSCode extension with Vue utilizing the VSCode webview. However, when attempting to import the compiled index.html into my extension, I consistently receive a prompt to enable JavaScript. Is there a solution for integrating Vu ...

What's the point of using defer() in Node.js Q promises when you have the option to simply use this

I had a plan in mind: somePromiseFunc(value1) .then(function(value2, callback) { // insert the next then() into this function: funcWithCallback(callback); }) .then(function(dronesYouAreLookingFor){ // Let's celebrate }) .done(); Unfortun ...

How does the call method on array.prototype.includes work with arguments x and y?

Curious about the functionality of array.prototype.includes.call(x, y);. Discovered that includes() confirms if an array has the specified value and provides a true or false result. Learned that call() invokes this alongside any optional arguments. The ...

JavaScript MP3 player

Could someone kindly point out where I went wrong? I am attempting to create an MP3 player using CSS, HTML, and JavaScript. Currently, the script only functions to start or stop the audio file. However, I keep encountering an error message: TypeError: docu ...

Python Error: item cannot be iterated

I'm fairly new to working with Python, and I need to create a function that reads specific columns from multiple text files and returns the values in a list for each file. I attempted to compile an array containing all the files I want to read and pa ...

What is the process for generating a matrix with negative index positions?

I'm looking to generate a unique matrix with numpy by doing the following: np.zeros([800, 200]) Is there a way for me to create a matrix that includes negative indices? For example, a 1600x200 matrix with row indices ranging from -800 to 800? ...

Best approach for integrating a Three.js project into a Ruby on Rails application?

Struggling to integrate a Three.js project into the Ruby on Rails framework I can't help but feel like there must be a simpler way to accomplish this task compared to my current methods Initially, I searched for a guide or tutorial on how to transfe ...

Can a Vue component in SFC form be utilized as a mixin?

Consider this scenario, where I have a component created in SFC format: // Parent.vue <template> <div> {{ txt }} </div> </template> <script> export default { name: 'ParentComponent', data() { return ...

Encountering a bindings issue when trying to utilize libxml-xsd within an electron application

Seeking guidance on validating an XML file against its schema within an electron application. Prior to adding the 'libxml-xsd' require statement to my angular2 service, it functioned properly. However, upon inclusion of this statement: const xs ...

Traversing JSON data in PHP

Currently, I am utilizing json_decode along with TRUE to dissect a JSON response within PHP. Despite my efforts, when attempting to retrieve its elements, I encounter issues. Here is an example of how the response appears: BCLS.secondaryCallResponse({"ite ...

The npm copy script is not functioning properly on the Windows 8.1 operating system

I am working on a sapui5 project and I need to execute the following npm script from my package.json: "scripts": { "flatten": "copy -r \\dist\\resources\\test\\commonjslib\\* dis ...