Working with JavaScript to push numerous results generated by a for loop into an array

I have developed a simple system that identifies users with matching genre interests as a specific user. I am trying to store the results of the for loop in an array, but currently only the last output is being added. I want all matching results to be included in the array. Any suggestions?

// User database
var jon = {username: 'Jon', genrePref: 'Rock'};
var lucy = {username: 'Lucy', genrePref: 'Pop'};
var mike = {username: 'Mike', genrePref: 'Rock'};
var luke = {username: 'Luke', genrePref: 'House'};
var james = {username: 'James', genrePref: 'House'};
var dave = {username: 'Dave', genrePref: 'Bass'};
var sarah = {username: 'Sarah', genrePref: 'Country'};
var natalie = {username: 'Natalie', genrePref: 'Bass'};

//userProfile.push()

// User database array
var userProfile = [jon, lucy, mike, luke, james, dave, sarah, natalie];


// Object containing username of logged in user and specification of the loaded track's genre
var trackGenre = {username: 'Harry', trackGenre: 'Rock'};

// For loop listing usernames of users with genre preference matching the distributed track
for(i = 0; i < userProfile.length; i++){

  if(userProfile[i].genrePref == trackGenre.trackGenre){

    console.log(userProfile[i].username);

    var matches = [];

    matches.push(userProfile[i].username);

  }
}

console.log(matches)

Answer №1

Consider moving the var declaration up to avoid reinitializing it each time and clearing it out:


var trackGenre = {username: 'Harry', trackGenre: 'Rock'};
var matches = [];

// Loop through user profiles to find matches based on genre preference
for(i = 0; i < userProfile.length; i++){

    if(userProfile[i].genrePref == trackGenre.trackGenre){

        console.log(userProfile[i].username);
        matches.push(userProfile[i].username);

    }
}

Answer №2

In response to the previous answer by @Montagist, I wanted to present two different methods to achieve the desired outcome. The first method utilizes the Array.prototype.forEach() instead of a traditional for loop to iterate over the array of users:

// User database
var jon = {
  username: 'Jon',
  genrePref: 'Rock'
};
var lucy = {
  username: 'Lucy',
  genrePref: 'Pop'
};
// Remaining user objects...
var userProfile = [jon, lucy, /* Additional users */];

// Object with user data for track comparison
var trackGenre = {
    username: 'Harry',
    trackGenre: 'Rock'
  },
  matches = [];

// Using Array.prototype.forEach() to iterate over users and find matches
userProfile.forEach(function(user) {
  if (user.genrePref === trackGenre.trackGenre) {
    matches.push(user.username);
  }
});

console.log(matches) // Example output: ["Jon", "Mike"]

JS Fiddle demo.

Another approach involves both Array.prototype.map() and Array.prototype.filter():

// User database
var jon = {
  username: 'Jon',
  genrePref: 'Rock'
};
var lucy = {
  username: 'Lucy',
  genrePref: 'Pop'
};
// Remaining user objects...
var userProfile = [jon, lucy, /* Additional users */];

// Object with user data for track comparison
var trackGenre = {
    username: 'Harry',
    trackGenre: 'Rock'
  },

  // Using Array.prototype.map() and Array.prototype.filter() to find matches
  matches = userProfile.map(function(user) {
    if (user.genrePref === trackGenre.trackGenre) {
      return user.username;
    }
  }).filter(Boolean);

console.log(matches) // Example output: ["Jon", "Mike"]

JS Fiddle demo.

References:

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

Error in Next.js Image Component: Missing SRC

Encountering an error with the next.js image component, specifically related to a missing "src" property. Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Th ...

Struggling with jQuery and the "hash" functionality?

I am encountering issues with jQTouch. The problem arises when I try to use this link: <a href="#site_map" class="swap">Map</a> and initialize jQTouch like this: var jQT = new $.jQTouch({ icon: 'jqtouch.png', ...

bxSlider adds in an empty slide after deleting an image

Whenever I click a link in my navigation, I want to remove certain images from the page. I tried implementing a solution, but now I have two empty spaces where the images used to be. How can I remove those as well? I searched on Stack Overflow for a soluti ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

Determine if a MySQL query in node.js returns no results

I'm trying to determine if there are no matching results in MySQL using Node.js. How can I achieve this? mysql.query("select * from table1 where name = 'abcd'", function(error, result, field) { if(error) { handleNoError(error); ...

Tips on how to direct the attention to a text box within a unique dialog, ensuring that the blinking cursor highlights the input area

Is there a way to set autofocus on a textbox when opening a custom dialog box? I've tried using the autofocus attribute for the input field, but it doesn't seem to work for me. Can anyone provide guidance on how to achieve autofocus for a textfie ...

Update the variables upon a click event following the completion of an AJAX request

Despite my efforts, I am unable to find a solution to the issue I am currently facing. To address this problem, I have created a script using PHP and jQuery that enables users to promote their "listings" on my website. When users visit a specific page, the ...

Utilizing array iteration to display images

I am having trouble getting the images to display on my card component. The description appears fine, but the images are not rendering properly even though I have the image data in an array. Here is the Card Component code: export const Card = (props) =&g ...

Having trouble resetting a checked checkbox label in Vuejs?

uncheck: function(checkedName) { this.checkedNames = this.checkedNames.filter(name => name !== checkedName); }, uncheckall: function(event) { this.checkedNames = []; }, checkedInput(event) { if (this.checkedNames.includes(event.targ ...

Tips for handling an empty jQuery selection

Below is the code snippet: PHP CODE: if($data2_array[7]['status'] == "OK"){ $degtorad = 0.01745329; $radtodeg = 57.29577951; $dlong = ($lng - $supermercado_lng); $dvalue = (sin($lat * $degtorad) * sin($superm ...

Examining Vuex Mutations using Jest confirms no alteration in state

I am currently facing an issue with testing a namespaced Vuex module using Jest. Despite making mutations to the mocked state, I am not seeing any changes reflected. Below is the code for my addEvents mutation: addEvents: (state, infos) => { t ...

The inline script is deemed non-compliant as it infringes upon the Content Security Policy directive: "script-src 'self'"

My chrome-extension is built using react-create-app. However, I encountered an error when running npm run build in react-create-app: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src &apo ...

I'm looking to add a price ticker to my html webpage. Does anyone know how to do this?

PHP Code <?php $url = "https://www.bitstamp.net/api/ticker/"; $fgc = file_get_contents($url); $json = json_decode($fgc, true); $price = $json["last"]; $high = $json["high"]; $low = $json["low"]; $date = date("m-d-Y - h:i:sa"); $open = $json["open"]; ...

What are the ways to activate an element in vue js?

Is there a way to modify the code so that the function triggers with just one click instead of two? export default { methods: { remove(){ $('.remove-me button').click( function() { removeItem(this); }); ...

Unable to find the matching closing parenthesis ')" before reaching the end

I've been struggling to create a regular expression that can identify strings like the ones below: var p1=@VAL([Test1Q1].[Bandwidth]) var p2=@VAL([Test1Q1].[Usages (KB)]) The criteria is to find strings starting with @VAL( and ending before the firs ...

Retrieve information from a MongoDB document based on the specific month

If I have a user document with a createdAt field, how can I retrieve data by month in the condition? The format of the createdAt value is as follows: 2016-10-08T16:21:40.935Z Account.find({'what should be passed here?'}, function(err,response){ ...

What is the recommended Vue js lifecycle method for initializing the materialize dropdown menu?

https://i.stack.imgur.com/cjGvh.png Upon examining the materialize documentation, it is evident that implementing this on a basic HTML file is straightforward: simply paste the HTML code into the body and add the JavaScript initializer within a script tag ...

Is there a way to create triangles on all four corners of an image using canvas in JavaScript?

In my code, I am currently working on drawing rectangles on the corners of an image using JavaScript. To achieve this, I first extract the image data from a canvas element. // Get image data let imgData = ctx.getImageData(0, 0, canvas.width, canvas.height) ...

Issue with MIME handling while utilizing Vue-Router in combination with Express

Struggling to access a specific route in Express, I keep encountering an error in my browser. Additionally, when the Vue application is built, only the Home page and the 404 page seem to work properly, while the rest display a default empty HTML layout. F ...