在数组javascript中排列对象

问题描述 投票:0回答:2

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

我想要的是每个对象的排名也是如此。因此,评级最高的对象也应该具有以下属性:“排名”: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);
});
};
javascript sorting ranking
2个回答
0
投票

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

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

0
投票

您可以将forEach循环中的某些索引/等级分配给movieslist,然后交换交换元素的等级以获得比较方法中的真实排名。见下文:

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);
});
};
© www.soinside.com 2019 - 2024. All rights reserved.