对数组 javascript 中的对象进行排名

Ranking objects in array javascript

我有一个 API 可以根据请求从数据库中获取所有对象(电影)。每个对象都有多个评级,用于计算该对象的一个​​主要评级。然后将每个对象推入一个数组。在发送 JSON-response 之前,该数组根据主要评级进行排序。评分最高的排在第一位。

我想要的是每个对象也有它的等级。因此,评分最高的对象也应该有一个 属性,如下所示:"ranking": 1.

我只是对在发送响应之前如何实现这一点感到困惑。这是我的代码:

const moviesListByRank = function (req, res) { 
let movieslist = [];
let movieMainRating = null;
Movie.find({}, function(err, movies){
    if(err) {
        console.log(err)
    } else {
        movies.forEach(function(movie){
            movieslist.push({
                name: movies.name,
                category: movie.category,
                movieMainRating: ((movie.FilterAction + hobby.FilterAdventure + movie.FilterRomantic)/3).toFixed(2),
                FilterAction: movie.FilterAction,
                FilterAdventure: movie.FilterAdventure,
                FilterRomatic: movie.FilterRomantic,
                _id: hobby._id
            });
        });
    }
    function compare(a,b){
        if (b.movieMainRating < a.movieMainRating)
            return -1;
        if (b.movieMainRating > a.movieMainRating)
            return 1;
        return 0;
    }
    movieslist.sort(compare);

    res
        .status(200)
        .json(movieslist);
});
};

一个简单的方法是;在 movieslist.sort(compare); 创建另一个 for 循环之后,forEach 也 returns 一个您可以使用的索引。

movieslist.forEach(function(movie, index){
   movie.rank = index + 1;
});

你可以将forEach循环中已经存在的index/rank赋值给movieslist,然后交换交换元素的排名,在compare方法中得到真正的排名。 见下文:

const moviesListByRank = function (req, res) { 
let movieslist = [];
let movieMainRating = null;
Movie.find({}, function(err, movies){
    if(err) {
        console.log(err)
    } else {
        var tempIndex = 0;
        movies.forEach(function(movie){
            movieslist.push({
                ranking: tempIndex++,
                name: movies.name,
                category: movie.category,
                movieMainRating: ((movie.FilterAction + hobby.FilterAdventure + mo
vie.FilterRomantic)/3).toFixed(2),
                FilterAction: movie.FilterAction,
                FilterAdventure: movie.FilterAdventure,
                FilterRomatic: movie.FilterRomantic,
                _id: hobby._id
            });
        });
    }
    function compare(a,b){
        if (b.movieMainRating < a.movieMainRating) {
            var tempRank = b.ranking;
            b.ranking = a.ranking;
            a.ranking = tempRank;
            return -1;
        }
        if (b.movieMainRating > a.movieMainRating)
            return 1;
        return 0;
    }
    movieslist.sort(compare);

    res
        .status(200)
        .json(movieslist);
});
};