Skip to content

Instantly share code, notes, and snippets.

@stoneboyindc
Last active June 9, 2021 01:55
Show Gist options
  • Save stoneboyindc/1b298074eb23b13c8eea431699a9b72f to your computer and use it in GitHub Desktop.
Save stoneboyindc/1b298074eb23b13c8eea431699a9b72f to your computer and use it in GitHub Desktop.
getMostCommonGenres()
function getMostCommonGenres(books) {
let countObj = {};
books.forEach(aBook => {
if (countObj[aBook.genre] != null) {
countObj[aBook.genre]++;
} else {
countObj[aBook.genre] = 1;
}
});
let countArray = [];
for (const [key, value] of Object.entries(countObj)) {
countArray.push({
'name' : key,
'count' : value
});
}
countArray.sort((a,b) => b.count - a.count);
return countArray.slice(0, 5);
}
function getMostCommonGenres(books) {
let result = {};
let genre = books.forEach((book) => {
if (result[book.genre] == null) {
result[book.genre] = 1;
} else {
result[book.genre] += 1;
}
})
let countArray = [];
for (const [key, value] of Object.entries(result)) {
countArray.push({
'name' : key,
'count' : value
});
}
countArray.sort((a,b) => b.count - a.count);
return countArray.slice(0, 5);
}
@stoneboyindc
Copy link
Author

stoneboyindc commented May 10, 2021

function helper(books) {
 let countObj = {};
  books.forEach(aBook => {
    if (countObj[aBook.genre] != null) {
      countObj[aBook.genre]++;
    } else {
      countObj[aBook.genre] = 1;
    }
  }
 return countObj;
}

function getMostCommonGenres(books) { 
  let countObj = helper(books);
  let countArray = [];
  for (const [key, value] of Object.entries(countObj)) {
    countArray.push({
      'name' : key,
      'count' : value
    }); 
  }
  countArray.sort((a,b) => b.count - a.count);
  return countArray.slice(0, 5);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment