Skip to content

Instantly share code, notes, and snippets.

@KashifAhmed
Created June 21, 2019 08:16
Show Gist options
  • Save KashifAhmed/2b7c8df2a98b7244326ecda09a414821 to your computer and use it in GitHub Desktop.
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.
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