Reputation: 15
I have this array
array = [{name:name,score:2},{name:name2,score:2},{name:name3,score:3},{name:name4,score:4},{name:name5,score:4}]
Please help me to get any highest and lowest occurence(score) of this array.
highestoccurence = [{name:name4,score:4},{name:name5,score:4}]
lowestoccurence = [{name:name,score:2},{name:name2,score:2}]
Thanks
Upvotes: 1
Views: 1116
Reputation: 34914
Check separately for higher
and lower
and make array
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);
Upvotes: 0
Reputation: 8543
Take a look at Lodash.
const maxItems = _.filter(array, { score: _.maxBy(array, 'score').score });
const minItems = _.filter(array, { score: _.minBy(array, 'score').score });
_.maxBy(array, 'score')
returns the first max score item.
_.filter(array, { score: maxItem.score })
will return items that have same score as the max one.
Upvotes: 1
Reputation: 320
First find min and max values:
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;
}
});
And then filter your array using that information:
var highestoccurence = array.filter(function(el) {
return el.score == max;
});
var lowestoccurence = array.filter(function(el) {
return el.score == min;
});
Upvotes: 1
Reputation: 10458
you can do it in the following way
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);
Upvotes: 1