[英]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. 我要尝试做的是创建一个数组,在该数组中,我将保持对已评级电影的用户的电影评级。.根据my_ratings大小的长度,我需要将这些用户放在单独的数组中。 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].. 这意味着,如果我的评级是由3部电影制作的,则我必须具有movie_users [1] =对该电影也评级为1 ...的所有user_id,与movie_users [2]和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. 在第一个循环中,在user_movie_rating
设置带有实际评级对象的哈希表,在第二个循环中,在my_ratings
检查并通过实际索引将userId
推送到movie_users
。
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. 使用ES6,您可以使用Set
而不是对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.