简体   繁体   中英

javascript append to array dynamically index

what i am trying to do is to create an array in which i will keep movie ratings from users who had rate the same movies that i have rate..i need those users in separate array depending on the length of my_ratings size. That means if my ratings was made from 3 movies i must have movie_users[1] = all user_ids who have rate also this movie 1...same for movie_users[2] and movie_users[3]..

    for(var i = 0; i < my_ratings.length; i++){
       for(var j=0; j < user_movie_rating.length; j++){
         if(my_ratings[i].movie_id == user_movie_rating[j].movieId){
           movie_users[i].push(user_movie_rating[j].userId);
          }
       }                             
   }

how can i do that?

You could use a hash table and iterate only once for both arrays.

In the first loop over user_movie_rating set the hash table with the actual rating object and in the second loop over my_ratings check and push userId to movie_users with the actual index.

var hash = Object.create(null);

user_movie_rating.forEach(function (rating) {
    hash[rating.movieId] = rating;
});

my_ratings.forEach(function (rating, i) {
    if (hash[rating.movie_id]) {
        movie_users[i].push(hash[rating.movieId].userId);
    }
});

With ES6 you could use Set instead of an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM