Utilizing Lodash for Effective Grouping of Arrays of Objects

Here is an example of an array of objects:

[
    {
       item: "123",
       categories: [A,B,C]
      },
    {
       item: "456",
       categories: [B,C]
      },
      {
       item: "789",
       categories: [C,D,E]
      }
]

I'm exploring using Lodash in typescript to group this data by category and generate the following output:

[
    {
       category: A,
       Items: ["123"]
      },
      {
       category: B,
       Items: ["123","456"]
      },
      {
       category: C,
       Items: ["123","456","789"]
      },
      {
       category: D,
       Items: ["789"]
      },
      {
       category: E,
       Items: ["789"]
      }
]

Answer №1

I can't seem to find an existing opt-in lodash function that fits your specific needs. Therefore, I have created a custom function called fn which should address your requirements.

function fn(input) {
  const allFeatures = input.reduce((features, cur) => {
    return _.uniq(_.concat(features, cur.features))
  }, [])

  return allFeatures.map(feature => ({
    feature,
    Products: input.filter(prod => prod.features.includes(feature)).map(x => x.product)
  }))
}

const input = [
  {
    product: 'ABC',
    features: [1, 2, 3]
  },
  {
    product: 'CDE',
    features: [1, 2]
  },
  {
    product: 'XYZ',
    features: [3, 4, 5]
  }
]

const expected = [
  {
    feature: 1,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 2,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 3,
    Products: ['ABC', 'XYZ']
  },
  {
    feature: 4,
    Products: ['XYZ']
  },
  {
    feature: 5,
    Products: ['XYZ']
  }
]
console.log('equal expected: ', _.isEqual(fn(input), expected))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

or

function fn(input) {
  const allFeatures = input.reduce((features, cur) => {
    return _.uniq(_.concat(features, cur.features))
  }, [])

  return allFeatures.map(feature => ({
    feature,
    Products: input.reduce((prods, cur) => cur.features.includes(feature) ?  prods.concat(cur.product) : prods, [])
  }))
}

const input = [
  {
    product: 'ABC',
    features: [1, 2, 3]
  },
  {
    product: 'CDE',
    features: [1, 2]
  },
  {
    product: 'XYZ',
    features: [3, 4, 5]
  }
]

const expected = [
  {
    feature: 1,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 2,
    Products: ['ABC', 'CDE']
  },
  {
    feature: 3,
    Products: ['ABC', 'XYZ']
  },
  {
    feature: 4,
    Products: ['XYZ']
  },
  {
    feature: 5,
    Products: ['XYZ']
  }
]
console.log('equal expected: ', _.isEqual(fn(input), expected))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

I'm excited to discover if there are more efficient solutions out there.

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

Troubleshooting Angular: Unidentified property 'clear' error in testing

I've implemented a component as shown below: <select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2"> <option value="tab1">First tab</option> <op ...

Understanding the Typescript Type for a JSON Schema Object

When working with JSON-schema objects in typescript, is there a specific type that should be associated with them? I currently have a method within my class that validates whether its members adhere to the dynamic json schema schema. This is how I am doing ...

How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet Alert Component import { Component, OnInit, Output } from '@angula ...

Utilize JSX attributes across various HTML elements

I'm looking for a solution to efficiently add JSX attributes to multiple elements. Here are the example attributes I want to include: class?: string; id?: string; style?: string; And here are the example elements: namespace JSX { interface Int ...

Typescript encounters difficulty locating the designated interface

Within my Aurelia View-Model, I am working on a Typescript file that contains the following structure: import {Chart} from './chart'; interface IMargin { top: number, right: number, bottom: number, left: number } export class App{ cha ...

Can you point me to the source of definition for Vue 2's ComponentDefinition and ComponentConstructor types?

I am struggling to add a dynamic Vue 2 component with correct typing in TypeScript. The documentation clearly mentions that the is attribute accepts values of type string | ComponentDefinition | ComponentConstructor, but I cannot locate these custom types ...

What is the best way to showcase a random index of an array in typescript?

Imagine a scenario where you have created a method that captures an array and selects a random position from it. The task at hand is to display one or more of these random positions on the screen. While you have successfully used the *ngFor directive to di ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

How can you dynamically disable a radio option button using Angular rendering without relying on an ID?

Is there a way to disable the male radio button without using an id, and utilizing angular rendering2? It seems like it's not working for me. I need to make this change only in the form.ts file, without altering the HTML code. form.html <label& ...

Starting up various modules in Angular 6 using arrays

Can an array be declared and used to bootstrap multiple components in module.ts? I attempted the following: export var initialComponents = []; initialComponents.push(AppComponent); if(condition) { initialComponents.push(IchFooterComponen ...

What are some methods for utilizing the "name" attribute within React components?

About My Coding Environment Utilizing TypeScript and ReactJS The Issue with Using name as an Attribute Encountering the following error: Type '{ name: string; "data-id": string; "data-type": string; }' is not assignable to ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Angular 2: Harnessing the power of dynamic backlinks on landing pages!

I am facing an issue with my Angular 2 item page. When a user lands on the page via a deep link, the Location.back() function does not work as there is no history in the Location object. To address this, I attempted to use a workaround where if the back() ...

Tips for converting JSON String data to JSON Number data

Hello everyone, I am facing an issue with converting the 'review' value from String to a numerical format in JSON. This is causing problems when trying to perform calculations, leading to incorrect results. The scenario involves saving user comm ...

Issues with NativeScript WebView displaying HTML file

Having trouble loading a local HTML file into a webview in my NativeScript (typescript) application. Despite using the correct path, it's not loading and instead shows an error. <WebView src="~/assets/content.html" /> An error message stati ...

An error has been detected: An unexpected directive was found. Kindly include a @NgModule annotation

I am encountering an issue while trying to import a class into a module in my Ionic/Angular app. Upon attempting to release, the following error message appears: ERROR in : Unexpected directive 'SeedModalPage in /home/robson/Lunes/repositories/bolunes ...

Guide on redirecting to the login page in angular2 when a process is left incomplete

I am facing an issue with the Popup used for device verification during login. When I click on the login button with valid credentials, a popup opens if the device is not trusted. Once I provide the necessary information and successfully validate, it shoul ...

Error TS2694 occurs in React when the namespace 'React' does not have an exported member. This issue typically arises when there is

Currently, I am attempting to incorporate the antd library into a React project that was created using Visual Studio 2017 (15.2.2). To start, I utilized the "ASP.NET Core Web Application" project template and selected "React.js" in the dialog below. http ...