Created
June 21, 2019 08:16
-
-
Save KashifAhmed/2b7c8df2a98b7244326ecda09a414821 to your computer and use it in GitHub Desktop.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let result = [{ | |
name: "Jhon", | |
rank: 3 | |
},{ | |
name: "Smith", | |
rank: 1 | |
},{ | |
name: "Kyel", | |
rank: 4 | |
},{ | |
name: "Lee", | |
rank: 2 | |
}]; | |
function byOrder(array){ | |
// Sort the array by rank number - Assending | |
return array.sort(function(itemA, itemB){ | |
return itemA.rank - itemB.rank | |
}) | |
} | |
function avgRank(array){ | |
// Calculate the average rank | |
let total = 0; | |
array.forEach((item)=>{ | |
total+=item.rank | |
}); | |
return total/array.length | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment