Home > Software design >  How to sum the elements of an array and return a value
How to sum the elements of an array and return a value

Time:11-26

We have an array with the name (chess_players) and 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.

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

function returnName(theObject){

constant result = [];

for(let i = 0; i < theObject.length; i  ){
    theObject.reduce((acc, nom) => acc   nom.fact, 0);
    result[i]  = [i]
}
  
return result
  
}

console.log(returnName(chess_players));

I have problems with the sum and comparison of the points of each player and that the function returns the name of the player who has obtained the most points.

CodePudding user response:

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))

CodePudding user response:

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));

  • Related