简体   繁体   中英

Max element in an array in dailogflow

I am trying to calculate max element in an array. I tried this code but it is returning [object Object] Is there something i am missing while doing in dailogflow.

 function studentgroup(agent){ let games = [ { id: 1, name: 'Star Wars: Imperial Assault', votes: 3}, { id: 2, name: 'Game of Thrones: Second Edition', votes: 4 }, { id: 3, name: 'Merchans and Marauders', votes: 5 }, { id: 4, name: 'Eclipse', votes: 6 }, { id: 5, name: 'Fure of Dracula', votes: 2 } ]; let maxGame = games.reduce((max, game) => max.votes > game.votes? max: game); agent.add(`${maxGame}`); }

You can simply find the maximum element by iterating over the array.

 let games = [ { id: 1, name: 'Star Wars: Imperial Assault', votes: 3}, { id: 2, name: 'Game of Thrones: Second Edition', votes: 4 }, { id: 3, name: 'Merchans and Marauders', votes: 5 }, { id: 4, name: 'Eclipse', votes: 6 }, { id: 5, name: 'Fure of Dracula', votes: 2 } ]; maxElement = -Infinity; element = null for (const game of games) { if (game.votes > maxElement) { maxElement = game.votes; element = game; } } console.log(element)

The issue is that maxGame is an object. Using your example, that object will be

{ id: 4, name: 'Eclipse',  votes: 6 }

But agent.add() is expecting to send back a string. The default "string" form of an object is "[object Object]", as you've seen.

You probably want to return something that makes more sense when displayed or read aloud, so it might make more sense for that line to be something like

agent.add(`The winner, with ${maxElement.votes} votes, is ${maxElement.name}.`)

which, given the example, would say something like

The winner, with 6 votes, is Eclipse.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM