-2

I’m trying to discover the best way of selecting an object that has the highest specific property value (in this case, number of wrong answers) and return another property (the name). E.G. the following object should return Mark:

[
{name: "Henry", age: "NYN", attempts: 3, wrong: 2},
{name: "Mark", age: "NNNY", attempts: 4, wrong: 3},
{name: "Beth", age: "", attempts: 0, wrong: 0},
{name: "Sally", age: "YYNY", attempts: 4, wrong: 1},
]

What’s the best way of going about this (in JavaScript)? Thanks for any help!

user8758206
  • 2,106
  • 4
  • 22
  • 45
  • [Finding the max value of an attribute in an array of objects](//stackoverflow.com/q/4020796) – 001 Jun 17 '18 at 01:10
  • 2
    Possible duplicate of [Finding the max value of an attribute in an array of objects](https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects) – JoshG Jun 17 '18 at 01:12

2 Answers2

1

Here's a simple way:

var objArray=[
{name: "Henry", age: "NYN", attempts: 3, wrong: 2},
{name: "Mark", age: "NNNY", attempts: 4, wrong: 3},
{name: "Beth", age: "", attempts: 0, wrong: 0},
{name: "Sally", age: "YYNY", attempts: 4, wrong: 1},
];
function getNameOfMostWrong(){
  //Set first object in array for most wrong as default
  var mostWrongPerson=objArray[0];
  for(var person in objArray){
    if(objArray[person].wrong > mostWrongPerson.wrong){
      mostWrongPerson=objArray[person];
    }
  }
  return mostWrongPerson.name;
}
Ramenous
  • 218
  • 1
  • 8
1

You can make simple for loop to check the highest wrong value and select that object. This will have complexity of O(n) which is similar to that to the linear search algorithm.

var arr = [
{name: "Henry", age: "NYN", attempts: 3, wrong: 2},
{name: "Mark", age: "NNNY", attempts: 4, wrong: 3},
{name: "Beth", age: "", attempts: 0, wrong: 0},
{name: "Sally", age: "YYNY", attempts: 4, wrong: 1},
];

var highest = arr[0].wrong, index;
for(var i=1; i<arr.length; i++){
  if(arr[i].wrong > highest){
     highest = arr[i];
     index = i;
  }
}
var highestWrong = arr[index];
console.log('highest wrong attempt is done by', highestWrong.name);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62