Javascript返回数组中得分最高的出现

时间:2017-09-07 05:40:40

标签: javascript arrays ecmascript-6

我有这个数组

array = [{name:name,score:2},{name:name2,score:2},{name:name3,score:3},{name:name4,score:4},{name:name5,score:4}]

请帮助我获得此阵列的最高和最低出现次数(分数)。

最高

highestoccurence = [{name:name4,score:4},{name:name5,score:4}]

lowestoccurence = [{name:name,score:2},{name:name2,score:2}]

由于

4 个答案:

答案 0 :(得分:1)

你可以通过以下方式完成



let array = [{name:'name',score:2},{name:'name2',score:2},{name:'name3',score:3},{name:'name4',score:4},{name:'name5',score:4}];


let max = array.reduce(function(a, b){
    if(a.score > b.score)
        return a;
    return b;
})

max_array = array.filter(function(element){
    return element.score == max.score;
});

console.log(max_array);






let array = [{name:'name',score:2},{name:'name2',score:2},{name:'name3',score:3},{name:'name4',score:4},{name:'name5',score:4}];


let min = array.reduce(function(a, b){
    if(a.score < b.score)
        return a;
    return b;
})

min_array = array.filter(function(element){
    return element.score == min.score;
});

console.log(min_array);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首先找到最小值和最大值:

var array = [{name:'abc',score:2},{name:'gdf',score:2},{name:'ghd',score:3},{name:'asdf',score:4},{name:'qwer',score:4}];

var max = -Infinity; 
var min = +Infinity; 

array.forEach(function(obj) {
    if(obj.score > max) {
        max = obj.score;
    }
    if(obj.score < min) {
        min = obj.score;
    }
});

然后使用该信息过滤您的数组:

var highestoccurence = array.filter(function(el) {
    return el.score == max;
});

var lowestoccurence = array.filter(function(el) {
    return el.score == min;
});

答案 2 :(得分:0)

看看Lodash

const maxItems = _.filter(array, { score: _.maxBy(array, 'score').score });
const minItems = _.filter(array, { score: _.minBy(array, 'score').score });

_.maxBy(array, 'score')会返回第一个最高分数项目。

_.filter(array, { score: maxItem.score })将返回与最大值相同的项目。

答案 3 :(得分:0)

单独检查higherlower并制作数组

array = [{name:"name",score:2},{name:"name2",score:2},{name:"name3",score:3},{name:"name4",score:4},{name:"name5",score:4}];
highest = [];
highestScore = 0;
lowest = [];
lowestScore = 0;
for(i in array){
  if(i == 0){
    lowestScore = array[i].score;
    highestScore = array[i].score;
    lowest.push(array[i]);
    highest.push(array[i]);
  }else{
    if(array[i].score <= lowestScore){
      if(array[i].score != lowestScore){
        lowest = [];
        lowestScore = array[i].score;  
      }
      lowest.push(array[i]);
    }
    if(array[i].score >= highestScore){
      if(array[i].score != highestScore){
        highest = [];
        highestScore = array[i].score;  
      }
      highest.push(array[i]);
    }
  }
}

console.log("lowest",lowest);
console.log("highest",highest);