【问题标题】:Finding the top ranked object in an array [closed]在数组中查找排名最高的对象[关闭]
【发布时间】:2021-10-19 06:27:45
【问题描述】:

我将带有名称和等级属性的电影对象存储在一个数组中 如何找到排名最高的对象?

【问题讨论】:

  • 你能给我们一个你实际拥有的代码示例吗?对象表示?
  • 如果您有一个对象数组,类似于:{name: "foo", rank: 1},那么您可以简单地按降序模式的 rank 属性排序并获取数组的第一个对象。签出this
  • [ {name : 'A', rank: 1}, {name : 'B', rank : 2}, {name : 'C', rank:3} ]

标签: javascript arrays javascript-objects


【解决方案1】:

您可以使用reduce

let array = [{"name":"XYZ","rank":1},{"name":"ABC","rank":2}];
let max = array.reduce(function(prev, current) {
    return (prev.rank > current.rank) ? prev : current
})

console.log(max);

【讨论】:

    【解决方案2】:

    这是 reduce 概念的替代解决方案。它返回一个电影对象数组(因为:通常两部电影或多部电影可以具有相同的排名)。

    const movies = [
        { name: 'Avatar', rank: 95 },
        { name: 'Harry Potter', rank: 80 },
        { name: 'Lord of the Rings 1', rank: 95 },
    ];
    
    const movieRanks = movies.map((movie) => { return movie.rank; });
    const highestMovieRank = Math.max(... movieRanks);
    const highestRankedMovies = movies.filter((movie) => { return movie.rank === highestMovieRank});
    
    // first occurence is the highest ranked movie
    const highestRankedMovie = highestRankedMovies[0];
    
    console.log(highestRankedMovies);

    【讨论】:

    • 排名第一的是#1。
    【解决方案3】:

    你好 这个可以帮到你:

    function FindTopRankedMovie(movies){
    let topRankIndex=0;
    for(let i=1;i<movies.length;i++)
         {
          /*here we loop all the array and compare the ranks and keep 
          highest rank in topRankIndex variables and return it at the end */       
         if(movies[i].getRank>movies[topRankIndex].getRank)
            topRankIndex=i;
    
         }
     return topRankIndex;
    }
    

    在主页面中,您使用以下功能:


    let top=FindTopRankedMovie(movies); 
    echo "The top ranked Movie is"+movies[top];
    

    【讨论】:

      猜你喜欢
      • 2016-06-09
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多