Skip to content

Instantly share code, notes, and snippets.

@davidsheardown
Created December 5, 2018 06:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidsheardown/9b23a7d300ecc6df58a240608568d8d5 to your computer and use it in GitHub Desktop.
Save davidsheardown/9b23a7d300ecc6df58a240608568d8d5 to your computer and use it in GitHub Desktop.
Javascript (Underscore Lib) Find top occurrences within a JSON array
// If we have a JSON object as such..
var data = [
{id:0, name: Name1, type: Error},
{id:1, name: Name2, type: Error},
{id:2, name: Name1, type: Error},
{id:3, name: Name1, type: Error},
{id:4, name: Name3, type: Error}
]
// Using underscore, we can get the top occurrences, in this case the top 5 (slice)
var topErrors = _.chain(data) // Wrap the operations below so we can return "value" from the subsequent functions
.countBy(function (item) { return item.name; }) // Get a count based on a JSON property
.pairs()
.sortBy(function (item) { return item[1]; })
.reverse()
.map(function (item) { return _.findWhere(data, { taskName: item[0], type: "Error" }); }) // Select our utem based on any other criteria
.value()
.slice(0, 5); // Return the top 5 in this case
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment