Created
December 5, 2018 06:42
-
-
Save davidsheardown/9b23a7d300ecc6df58a240608568d8d5 to your computer and use it in GitHub Desktop.
Javascript (Underscore Lib) Find top occurrences within a JSON array
This file contains 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
// 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