I have the following multidimensional array of student objects:
var students = [
{name: \"Jack\", age: \"NYN\", attempts: 3, wrong: 2},
{name: \"Phil\", age: \"N
The most straight-forward algorithm to achieve your goal would be:
wrong
within students
array.filter
to leave only the relevant students (with the property wrong
equals the maximum).var students = [{name: "Jack", age: "NYN", attempts: 3, wrong: 2},{name: "Phil", age: "NNNY", attempts: 4, wrong: 3},{name: "Tom", age: "", attempts: 0, wrong: 0},{name: "Lucy", age: "YYNY", attempts: 4, wrong: 1},{name: "Ben", age: "NYNN", attempts: 4, wrong: 3},{name: "Hardest", age: "NNN", attempts: 3, wrong: 3}];
// Find the maximum 'wrong' value
let maxValue = 0;
for(let student of students) {
if(student.wrong > maxValue) {
maxValue = student.wrong;
}
}
// filter out the students with 'wrong' value different than the maximum
let onlyMax = students.filter(item => item.wrong == maxValue);
console.log(onlyMax);
Note all the algorithm does is iterating the array twice, resulting in run-time of O(2n) = O(n).
The more general solution allows one to find the items with maximum value of property
in an objects array:
var students = [{name: "Jack", age: "NYN", attempts: 3, wrong: 2},{name: "Phil", age: "NNNY", attempts: 4, wrong: 3},{name: "Tom", age: "", attempts: 0, wrong: 0},{name: "Lucy", age: "YYNY", attempts: 4, wrong: 1},{name: "Ben", age: "NYNN", attempts: 4, wrong: 3},{name: "Hardest", age: "NNN", attempts: 3, wrong: 3}];
function filterByMax(arr, property) {
// Find the maximum 'wrong' value
let maxValue = 0;
for(let item of arr) {
if(item[property] > maxValue) {
maxValue = item[property];
}
}
// filter out the students with 'wrong' value different than the maximum
return arr.filter(item => item[property] == maxValue);
}
console.log(filterByMax(students, 'wrong'));