I have created a basic system to output users that match with the same genre interests as a specified user. I want to push the results of the for loop into an array however I can only get the last for loop output to be pushed into the array but I want all of the results to be 'pushed'. 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 the same as the distributed track
for(i = 0; i < userProfile.length; i++){
if(userProfile[i].genrePref == trackGenre.trackGenre){
console.log(userProfile[i].username);
var matchs = [];
matchs.push(userProfile[i].username);
}
}
console.log(matchs)
var matchs = [];outside of the loop. You're creating a new array on each iteration and so you're only getting the value of the last iteration. Also, get in the habit of declaring your loop vars:for (var i.