Skip to content

Instantly share code, notes, and snippets.

@p8ul
Created June 19, 2019 11:41
Show Gist options
  • Save p8ul/64bfc063293ae0a05af26397704aada8 to your computer and use it in GitHub Desktop.
Save p8ul/64bfc063293ae0a05af26397704aada8 to your computer and use it in GitHub Desktop.
Two functions to 1. Sort a javascript array 2. Return average ranking
const arr = [
{ name: "John", rank: 2 },
{ name: "Mathew", rank: 4 },
{ name: "Alex", rank: 1 },
]
/**
* @func sortArray
* @desc Sort an array of object by rank
* @params {Array} arr an array of objects
* @params {string} arr.name name of an object
* @params {number} arr.rank a number representing rank
* @returns {Array} a sorted array
*/
const sortArray = (arr = []) => {
const result = arr.sort((a,b) => (a.rank > b.rank) ? 1 : ((b.rnak > a.rank) ? -1 : 0));
return result
}
/**
* @func averageRank
* @desc Return average ranking
* @params {Array} arr an array of objects
* @params {string} arr.name name of an object
* @params {number} arr.rank a number representing rank
* @returns {number} average ranking
*/
const averageRank = (arr) => {
let tempArr = arr.map(obj => obj.rank);
let totalRanks = tempArr.reduce((accumulator, current) => accumulator + current )
return totalRanks / arr.length;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment