0

We have an array with the name; chess_players, in each element of the array there is an object with two properties: the name of a chess player and the points he has obtained. In this activity, a function must be created (which allows code reuse, that is, if the table is extended with more players, the function must continue to work without having to modify anything). The created function must receive the object as a parameter and return the name of the chess player who has obtained the most points.

This is what I tried:

let chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]},{name:"Steve",points:[300,400,900,1000,2020]}]

function returnName(object){
/* With this for in loop, I'm trying to iterate through each array to calculate the sum of each array */
  for (var num in object){
    var index = 0;
    var length = object.length;
    var sum = 0;
/* I try to return the maximum value */
    sum += object.fact[index ++]
    var maxVal = Math.max(...sum);
  }
  return array[index].name;
}

console.log(returnName(chess_players))


marioconde
  • 17
  • 5
  • see: [Sort by the sum of array in object](https://stackoverflow.com/questions/56598812/sort-by-the-sum-of-array-in-object) – pilchard Nov 26 '22 at 01:07

2 Answers2

0

I would perhaps use reduce method and calculate the total points of each player. then sort them descending order. and finally retrieve the name of player.

let chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]}, 
                     {name:"Steve",points:[300,400,900,1000,2020]}]
const returnName = theObject => 
  theObject.map(({name, points})=>({name, totalPoints:points.reduce((acc , current) => acc + current)})).sort((a,b)=> b.totalPoints - a.totalPoints)[0].name
console.log(returnName(chess_players))
  • I looked at the question and started solving . it took me 20 mins to solve, by then you already posted the solution. you are using ?. I'm a beginner and dont know, im just sorting descending order and getting the first value from the sorted array. – Vandhana Mohan Nov 26 '22 at 02:00
  • Thank you very much, but that's not exactly what I'm asking for either. I am also a beginner. I hope you can learn with this exercise. @VandhanaMohan – marioconde Nov 26 '22 at 14:39
0

Step by step:

const chess_players = [{name:"Jackson",points:[900,1000,3000,1950,5000]},{name:"Steve",points:[300,400,900,1000,2020]}]

function returnName(theObject){
    const arrOfTotalVal = theObject.map(obj => obj.points.reduce((a, c) => a + c));

    const maxVal = Math.max(...arrOfTotalVal);

    const index = arrOfTotalVal.indexOf(maxVal);

    return theObject[index].name;
}

console.log(returnName(chess_players));
Serj Woyt
  • 46
  • 3