简体   繁体   中英

Array of objects - return objects by order & return average ranking

This is a practice hw question.

INSTRUCTIONS

You have an array of objects in JavaScript. Each one contains a name (a string) and ranking (a number).

Write two functions, one to return the objects ordered by ranking and another to return the average ranking.

I have it sorted, but need to find the average ranking as well.

CODE

 let obj = [{name: "bob", ranking: 2}, {name: "rob", ranking: 3}, {name: "cob", ranking: 1}]; const output = obj .sort((a, b) => a - b); function avgRanking(num) { let sum = obj.reduce((previous, current) => current += previous); let avg = sum / obj.ranking.length; return avg } console.log(output); console.log(avgRanking()); // NaN 

What am I doing wrong?

.sort() sorts an array, and only that. If you start with an array of objects and call .sort() on it, the array will still be an array of objects, only (possibly) in a different order.

If you want a sorted array of just the rankings, you need to .map to extract the values (either before or after sorting). You should also probably use a better variable name for the array - it's an array, not a plain object, so perhaps name it arr or users (or something that more accurately describes what the collection is), else there's a good chance of confusion:

 const users = [{name: "bob", ranking: 2}, {name: "rob", ranking: 3}, {name: "cob", ranking: 1}]; const output = users .map(obj => obj.ranking) .sort((a, b) => a - b); console.log(output); 

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