How to use the groupBy function in Underscore.js

{
     collectionId: 1,
     category: 'a',
     collectionType: 'typea'
 }, {
     collectionId: 1,
     category: 'a',
     collectionType: 'typea'
 }, {
     collectionId: 1,
     category: 'b',
     collectionType: 'typea'
 }, {
     collectionId: 2,
     category: 'b',
     collectionType: 'typeb'
 }, {
     collectionId: 2,
     category: 'b',
     collectionType: 'typeb'
 },

What is the best approach for handling the following scenarios:

A) When there are 2 books with the same collection type and category: Both books should be grouped together and displayed as a collection in that particular category.

B) When there are 2 books with the same collection type but different categories: Both books should be grouped together and displayed as a collection on a separate shelf named "My Collection". (This shelf exists separately from other categories on the bookshelf.)

C) When there are 3 books with the same collection type but 2 of them have the same category while the 3rd has a different category: All 3 books should be grouped together and shown as a collection on a separate shelf named "My Collection". (This shelf exists separately from other categories on the bookshelf.)

Answer №1

var LIMIT = 2,
    C_LIMIT = 3;

// X
_(coll)
.chain()
.groupBy(i => i.collectionType.concat(i.category))
.findWhere(i => i.length > LIMIT)
.first(LIMIT)
.value();

// Y
_(coll)
.chain()
.groupBy('collectionType')
.mapObject(i => _(i).indexBy('category'))
.values()
.findWhere(i => _(i).keys().length >= LIMIT)
.values()
.first(LIMIT)
.value();

// Z
_(coll)
.chain()
.groupBy('collectionType')
.mapObject(function(i) {
    return _(i)
    .chain()
    .groupBy('category')
    .values()
    .map(v => _(v).first(LIMIT))
    .sortBy('length')
    .reverse()
    .flatten()
    .first(C_LIMIT)
    .value()
})
.values()
.findWhere(i => i.length === C_LIMIT)
.value(); 

var coll = [{
  collectionId: 1,
  category: 'a',
  collectionType: 'typea'
}, {
  collectionId: 1,
  category: 'a',
  collectionType: 'typea'
}, {
  collectionId: 1,
  category: 'b',
  collectionType: 'typea'
}, {
  collectionId: 2,
  category: 'b',
  collectionType: 'typeb'
}, {
  collectionId: 2,
  category: 'b',
  collectionType: 'typeb'
}];

var LIMIT = 2,
  C_LIMIT = 3,
  el = document.getElementById('result');

var x = _(coll)
  .chain()
  .groupBy(i => i.collectionType.concat(i.category))
  .findWhere(i => i.length > LIMIT)
  .first(LIMIT)
  .value();

var y = _(coll)
  .chain()
  .groupBy('collectionType')
  .mapObject(i => _(i).indexBy('category'))
  .values()
  .findWhere(i => _(i).keys().length >= LIMIT)
  .values()
  .first(LIMIT)
  .value();

var z = _(coll)
  .chain()
  .groupBy('collectionType')
  .mapObject(function(i) {
    return _(i)
      .chain()
      .groupBy('category')
      .values()
      .map(v => _(v).first(LIMIT))
      .sortBy('length')
      .reverse()
      .flatten()
      .first(C_LIMIT)
      .value()
  })
  .values()
  .findWhere(i => i.length === C_LIMIT)
  .value();

el.innerHTML = _([x, y, z]).map(x => JSON.stringify(x)).join('<br><br>');
<script src="http://underscorejs.org/underscore-min.js"></script>
<div id="result"></div>

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

Top method for utilizing jQuery to locate, sift through, and implement CSS classes

Let's consider the following scenario: <span class="foo">7</span> <span class="foo">2</span> <span class="foo">9</span> We want to assign a CSS class of 'highest' to 'span.foo' with value great ...

Server-side issue: Ajax POST request returns an empty POST array

I've encountered an issue with my JavaScript function that is supposed to collect data and send it to a PHP file. My problem lies in attempting to submit an array as part of the post: Here's the snippet of the function in question: var string ...

Adding a Material UI Tooltip to the header name of a Material UI Datagrid - a step-by-step guide!

I've nearly completed my initial project, but the client is requesting that I include labels that appear when hovering over specific datagrid cells. Unfortunately, I haven't been able to find any solutions on Google for adding a Material UI Tool ...

Fixing the error: "React-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a valid function"

Every time I change the option in the selector, I keep encountering this error: "react-dom.development.js:4091 Uncaught TypeError: onItemSelect is not a function" :( import React from "react"; import Product from "./Product" ...

Is there a way to show a fallback message for unsupported video file formats?

When incorporating a video element on my webpage, I typically use the following code: <video src="some source" controls> Error message </video> Based on my knowledge, the "Error message" will only appear if the browser does not support the ...

Aligning a picture at the center of the screen with CSS - Various screen and image sizes

For my project, I need to design a web page with a single image perfectly centered both vertically and horizontally on the screen. Here are the specific requirements: The client's screen size is unknown (mobile) The image will be user-defined with u ...

Do you typically define a static variable within a function using `this.temp`?

I am looking to implement a static variable within a function that meets the following criteria: It maintains its value across multiple calls to the function It is only accessible within the scope of that function Below is a basic example of how I am mee ...

What are some creative ways to utilize postMessage instead of relying on nextTick or setTimeout with a zero millisecond delay?

I just came across a theory that postMessage in Google Chrome is similar to nextTick. This idea somewhat confused me because I was under the impression that postMessage was primarily used for communication between web workers. Experimenting with expressio ...

The $firebaseObject variable is not defined

My AngularJs + AngularFire setup includes email/password authentication and a node called "users" to list authenticated users. Here is a snapshot: https://i.sstatic.net/eBz3G.png Within my authentication service, I have an AngularJs factory: .factory(&ap ...

How to boost the value of a property within a MongoDB document with Mongoose

Recently, I've been dealing with an array of objects named "items". This array includes different objects and I need to search for each object in MongoDB using the "baseId" found in the Base Document. Once I locate the matching object, I aim to update ...

Persistent column menu in ag-grid

Is there a way to include a menu for each row within a sticky column in Ag-grid? I couldn't find any information about this feature in the official documentation, so I'm unsure if it's even possible. I've attempted several methods, but ...

Retrieving the contents of a unique 404 error page using ajax

Currently attempting to retrieve the content of a custom 404 page through ajax (I need to extract a counter value from this page using Greasemonkey). Regrettably, jQuery's .fail method in ajax does not provide the option to access the page's con ...

Error when spaces are present in the formatted JSON result within the link parameter of the 'load' function in JQuery

I am facing an issue with JSON and jQuery. My goal is to send a formatted JSON result within the link using the .load() function. <?php $array = array( "test1" => "Some_text_without_space", "test2" => "Some text with space" ); $json = jso ...

Issue with express-validator returning undefined value on forms set to enctype='multipart/form-data'

Currently, I am developing a login authentication application using basic node.js+express. While extracting values (such as name, email, etc) from the registration page, I utilize express-validator for validation. However, I encounter an issue where all va ...

Unable to transfer data from Laravel's Blade template to a Vue component

Need help passing a value from Laravel to Vue. I'm facing an issue where the props I receive are always showing as undefined in the console.log output. I've double-checked for camel case errors but can't seem to find the root cause of the pr ...

Sending JSON data from PHP to JavaScript using Ajax

Currently, I am attempting to transfer a JSON object from a PHP script to a JavaScript file using Ajax. The code I have been using successfully for a single string is now being modified to accommodate multiple strings within a JSON object. Below are snippe ...

The .angular-cli.json file is causing issues with loading scripts

I have recently updated my .angular-cli.json file by adding new scripts in the following format: "apps": [ { "root": "src", "outDir": "dist", "assets": [ "assets", "favicon.ico" ], "index": "index.html ...

ngFor returning undefined despite array containing value

While iterating through an array using ngFor, I'm encountering an issue where trying to access data in the 'value' variable results in it being undefined. Why is this happening? myArray = ['a', 'b', 'c', 'd ...

Manipulating HTTP responses and variables in Angular 6

I created a custom application using the MEAN stack that allows users to sign up and log in. To enhance security, I want users to reconfirm their identity by entering their password or a PIN if they return to the application after some time. To achieve th ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...