Using lodash/underscore to aggregate, sort, and limit data

My data needs to be aggregated, and while MongoDB aggregation would make this easy, I prefer to do it on the client side. Utilizing LoDash or Underscore should help with this task.

Let's consider the sample data below:

var data = [
    {
        "uId" : "u1",
        "qId" : "q1",
        "share" : 2,
        "star"  :   2,
        "score" : 5
    },
    {
        "uId" : "u1",
        "qId" : "q2",
        "share" : 2,
        "star"  :   2,
        "score" : 5
    },
    {
        "uId" : "u2",
        "qId" : "q1",
        "share" : 2,
        "star"  :   2,
        "score" : 5
    },
    {
        "uId" : "u2",
        "qId" : "q2",
        "share" : 3,
        "star"  :   3,
        "score" : 7
    },
    {
        "uId" : "u3",
        "qId" : "q1",
        "share" : 3,
        "star"  :   3,
        "score" : 7
    },
    {
        "uId" : "u3",
        "qId" : "q2",
        "share" : 3,
        "star"  :   3,
        "score" : 7
    }
]

The desired result is as follows:

result = [
    {
        "uId" : "u3",
        "qId" : 2,
        "share" : 6,
        "star"  :   6,
        "score" : 14
    },
    {
        "uId" : "u2",
        "qId" : 2,
        "share" : 5,
        "star"  :   5,
        "score" : 12
    }
]

The output should be sorted by highest score and limited to showing only 2 results.

Thank you for your assistance.

Answer №1

Another option is to achieve this using underscore library.

_.sortBy(data, 'score').reverse().splice(0, 2);

It's uncertain how efficient the reverse operation would be in terms of performance.

UPDATE:

Found a way to eliminate the need for reverse:

_.sortBy(data, function (el) { return -el.score; }).splice(0, 2);

Answer №2

One way to accomplish this task is by utilizing the lodash library:

_.map(_.sortByOrder(collection, ['value'], ['asc']), _.values).slice(0,3);

This code snippet will first sort the collection in ascending order based on the 'value' property and then extract the first three elements from the sorted array.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Formik Material UI Localization Provider is not functioning properly when paired with the Luxon Adapter for formatting dates in

Currently, I am utilizing the MUI localization provider in conjunction with the luxon adapter to transform the date format to GB. However, despite my efforts, the date remains in the mm/dd/yyyy format rather than displaying as dd/mm/yyyy. Please refer ...

Guide to creating a unique React component for displaying a single popup upon clicking with the ability to pass props to it

As someone who is still learning React, I decided to challenge myself by creating a Jeopardy game using this framework. My current idea is to have a popup appear when a player clicks on a box on the Jeopardy board, displaying the clue associated with that ...

Utilizing Lodash efficiently with tree shaking

After experimenting with using lodash functions as a specific import versus as a destructured object, I noticed a significant difference in file size. When imported as shown below, the size is only 14.7KB. https://i.sstatic.net/avFcR.png However, when I t ...

Encountering obstacles when trying to implement mongoose virtuals in a TypeScript environment

I have been exploring how to utilize virtuals in mongoose with typescript. Let's say I have an interface for defining a user. interface User { id: mongoose.ObjectId; name: string; likes: string; } Next, I define a schema for mongoose. // ...

Interactive feature allowing all embedded YouTube videos on a webpage to play synchronously, with sound disabled, and on a continuous loop

I am in the process of developing a button that, when clicked by a user, will trigger all embedded YouTube videos on a specific webpage to start playing simultaneously, with sound muted, and set to loop. The target page for this button implementation can ...

What is the best way to transfer values or fields between pages in ReactJS?

Is there a way to pass the checkbox value to the checkout.js page? The issue I'm facing is on the PaymentForm page, where my attempts are not yielding the desired results. Essentially, I aim to utilize the PaymentForm fields in the checkout.js page as ...

The problem with the Next.js 14 generateStaticParamsparams parameter is that it is currently

I'm using this documentation as a reference to extract parameters from the URL in my generateStaticParams function: https://nextjs.org/docs/app/api-reference/functions/generate-static-params#generate-params-from-the-bottom-up This is the route I am w ...

JavaScript array remains unchanged

I have a sample of JSON data saved in the "data" variable. Here is the FORMAT : { "0" : {"names":"Pooja, Trivedi"}, "1" : {"names":"Pooja, Rooster"} } My objective is to create a map that can calculate the frequency of each name: Pooja = 2 Triv ...

Restrict Material-UI DatePicker to only allow the selection of the year using react

Struggling to configure a Material-UI DatePicker to only accept the year without letting the user input or select the month and day. I've attempted various solutions but nothing seems to be working. Does anyone know how to solve this issue? ...

Leveraging asynchronous data in a synchronous manner

I am dealing with tax rate data stored in the database to ensure easy updates when necessary. However, JavaScript's asynchronous nature complicates accessing this data as it requires promises or callbacks to retrieve query results. Is there a solution ...

Having trouble with getting the second JavaScript function to function properly?

I am facing an issue with the second JavaScript function. When I click the 'Send Mail' button, it should call the second function and pass it two values. However, the href line (second last line in the first function) is not rendering correctly. ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

Dealing with validations in a personalized aid

Recently, I've been exploring CodeceptJs and have found it quite easy to work with. Currently, I'm utilizing it with NightmareJs for testing a gallery that retrieves data from an interface via JSONP to create a list of images enclosed in <div& ...

Picture fails to load on Ionic app on the device

Currently, I am utilizing Ionic 3 for my project. The location of the images file is \src\assets\img. This pertains to a basic page implementation. export class BasicPage { items = []; constructor(public nav: NavController ,private adm ...

Error: 'err' has not been defined

Recently, I embarked on creating my very first API using Mongo, Express and Node. As I attempted to establish an API endpoint for a specific user, the console threw me this error: ReferenceError: err is not defined. Curiously, the same method worked flawle ...

Guide on filling out multiple forms with just one form

I am currently working on creating an online application where users can fill out the contact forms on my two other websites, located at and , using the form on my third website at . Essentially, when a user submits the form on , it should automatically ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

Changes in Property Data Source occur in the type/class of nested Custom Controls

Displayed here is a section of our internal log, showcasing the compositeData for 2 distinct custom controls - one being the caller and the other being the callee. This information is captured during the BeforePageLoad event. The parameter dataSource is p ...

When adding an object to an array in AngularJS, it seems to trigger updates for

Currently, I am fetching data from a WebAPI and then storing it in an array called products, which is scoped. $scope.products In addition to the products array, I also have another scoped array named selectedFish. $scope.selectedFish = []; My objective ...

Are non-local variables in Node.js considered safe to use?

Would it be secure to implement this code in Node.js/Express.js? // using Object.create(null) to avoid key collisions // refer http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ var theHash = Object.create(null); exports.store = function (req, ...