Determine whether the array of an object includes any elements from another array using Lodash

Each product in the array contains a unique structure that includes an ID, name, and materials list. The materials list consists of various materials with their own IDs and names.

{
  id: 1,
  name: "product 1",
  materials: [
    {
      id: 1,
      name: "material 1"
    },
    {
      id: 2,
      name: "material 2"
    },
    {
      id: 3,
      name: "material 3"
    }
  ]
}

Every product can have a different number of materials in its materials list.

In addition, there is a separate array containing material IDs such as [1, 4, 7, 2, 5].

The task at hand is to filter the array of products so that only products with materials whose IDs match those in the array of material IDs remain.

Answer №1

attempt

items.filter(item => item.parts.some(part => partIds.includes(part.id)));

let partIds = [1, 4, 7, 2, 5];
let items = [
{ id: 1, name: "item 1", parts: [{id: 1,name: "part 1"},{id: 2,name: "part 2"},{id: 3, name: "part 3"}]},

{ id: 2, name: "item 2", parts: [{id: 2, name: "part 2"}]},

{ id: 3, name: "item 3", parts: [{id: 3, name: "part 3"}]},

]

let filteredItems = items.filter(item => item.parts.some(part => partIds.includes(part.id)));

console.log('Filtered items ids', filteredItems.map(item => item.id));
console.log('Filtered items', JSON.stringify(filteredItems));

Answer №2

Here is a way to achieve this:

import {intersection} from 'lodash'
const products = [...] 
const materialIds = [1,4,7,2,5]

// Example of using ES5+ function
const targetProducts = products.filter(p => intersection(p.materials.map(m => m.id), materialIds).length)

// Achieve the same result using lodash functions only: import {filter, map, intersection} from 'lodash'
const targetProducts = filter(products, p => intersection(map(p.materials, 'id'), materialIds).length)

Answer №3

If you want to achieve this task, you can utilize JavaScript methods like filter(), some(), and includes().

  • Start by applying filter() on the main array of products
  • Then, use some() on the materials property of each object.
  • Check whether the mats (material ids) list includes the id of a material.

let arr = [{ id: 1, name: "product 1", materials: [ { id: 1, name: "material 1" }, { id: 2, name: "material 2" }, { id: 3, name: "material 3" } ] },{ id: 2, name: "product 2", materials: [ { id: 11, name: "material 11" }, { id: 22, name: "material 22" }, { id: 33, name: "material 33" } ] }];

let mats = [1, 5, 6];

let res = arr.filter(x => x.materials.some(z=> mats.includes(z.id)));

console.log(res)

Answer №4

const items = [
      {
        id: 1,
        name: 'item 1',
        components: [
          {
            id: 1,
            name: 'component 1'
          },
          {
            id: 7,
            name: 'component 7'
          },
          {
            id: 5,
            name: 'component 5'
          }
        ]
      },
      {
        id: 2,
        name: 'item 2',
        components: [
          {
            id: 1,
            name: 'component 1'
          },
          {
            id: 2,
            name: 'component 2'
          },
          {
            id: 3,
            name: 'component 3'
          }
        ]
      }
    ];
    const components = [3, 4];
    console.log(
      items.filter(item => {
        for (let i = 0; i < item.components.length; i++) {
          if (components.includes(item.components[i].id)) return true;
        }
      })
    );

I prefer this approach:

 products.filter(product => {
    for (let i = 0; i < product.materials.length; i++) {
      if (materials.includes(product.materials[i].id)) return true;
    }
  })

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

Enhance the efficiency of React code by optimizing the loading of data from multiple sources concurrently instead of one after another

In my project, there are 2 tabs displaying visualizations generated from separate data sources. Each tab requires multiple queries to be executed in the background to fetch the data, resulting in a delay when loading each tab individually. The current impl ...

Error Timeout Encountered by Langchain UnstructuredDirectoryLoader

I am facing an issue while trying to load a complex PDF file with tables and figures, spanning approximately 600 pages. When utilizing the fast option in Langchain-JS with NextJS Unstructured API, it partially works but misses out on some crucial data. On ...

Is it acceptable to utilize $$updated while expanding a firebase factory in order to execute a getTotal() method similar to the one demonstrated in the example

Is there a way for me to retrieve the data returned by $$updated or have $$updated trigger a function that I can then receive every time a task is marked as completed? By the end of the day, I need to maintain a count of how many tasks users have finished ...

Guidelines for generating and printing a receipt on a thermal printer using react.js and NodeJs?

After creating an office application to manage a supermarket using Windev, my client now wants to enable remote access and control over the internet. To achieve this, I am considering transforming the application into a web application using React.js in th ...

If the width of the table is set to 100% in the CSS, the legend in the Flot chart will automatically shift to the

When the CSS for the table is set to { width:100%}, the Flot chart's legend moves to the left side. Is there any way to maintain the table { width:100%} while also preventing this shift, considering that the CSS is applied site-wide? Here is a jsfid ...

The modal popup will appear in the center of the screen when the scrollbar is positioned at the top

I have a modal popup that is not consistently displayed in the center of the screen, regardless of the scrollbar position. I always want it to render at the center so the user doesn't need to scroll to see it. Below is the code I am currently using: ...

Deserialization of Newtonsoft Array with Index Key

I am utilizing the newtonsoft.Net library for Deserializing/Serializing Objects. Is it possible to Deserialize the JSON below as an Array of "OfferPixel" objects? Each object within the array is assigned an index number on the service. Therefore, the "Of ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Is there a way to ensure uniform display of HTML form error messages across various browsers?

Recently, I completed a login form that consists of username and password fields. For the username, I used a text field with the type email, while for the password, I utilized a text field with the type password which requires validation through a regex pa ...

Compel a customer to invoke a particular function

Is there a way to ensure that the build method is always called by the client at the end of the command chain? const foo = new Foo(); foo.bar().a() // I need to guarantee that the `build` method is invoked. Check out the following code snippet: interface ...

Interactive table created with DataTables that automatically updates the dynamic JSON data source whenever changes are made to the table

Using the Datatables plugin, I am dynamically populating a table with HTML rendered from a JSON array. However, I need the table to update the model (datasource) stored client-side whenever an edit is made. When navigating to a new page on the table, it s ...

Generate a table framework by dynamically adjusting the number of rows and columns

I'm running into an issue with my implementation of nested for-loops to dynamically generate a table using JavaScript. For this particular scenario, let's assume numRows = 2 and numCols = 6. This is the code snippet in question: let table = $( ...

Tips for effectively combining an array with jQuery.val

My goal is to have multiple form fields on a page, gather the input results into an array, and then store them in a database. This process was successful for me initially. However, when I introduced an autocomplete function which retrieves suggestions from ...

Use the evernote findNotesMetadata function to efficiently retrieve all notes by implementing an offset and maxnotes parameter for looping through

According to the documentation provided by Evernote regarding findNotesMetadata, the maximum number of notes returned from the server in one response is 250. I am currently exploring how to handle multiple requests in order to retrieve the entire array if ...

Positioning a Material UI Menu item underneath its parent element using CSS styling

I have created a Material UI dialog that features some text and an Icon with a dropdown menu option. You can check out the demo here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js My goal is to properly position the Menu component so that it a ...

What is the best way to utilize props and mounted() in NuxtJS together?

I'm a beginner with NuxtJS and I'm looking to implement window.addEventListener on a specific component within my page. However, I also need to ensure that the event is removed when the page changes. In React, I would typically approach this as ...

Configuring a JavaScript calendar with custom margins

Having trouble selecting a date with the Bootstrap datepicker class. After running the snippet, the calendar appears below the textbox: <input type="text" class="form-control datepicker" name="due_date" id="due_date" onclick="calendar_up()" value="" pl ...

Locating the value of a data attribute from a distant parent div using jQuery

How can I access the closest div from an anchor tag that has a data-id attribute without using multiple parent() methods? Even though .parent().parent().parent() works, I am trying to find a better solution. <div class="panel panel-default" data-id="@ ...

Retrieving data from a file results in receiving blank strings

Struggling to access the data within a directory of files, I've encountered an issue where the data doesn't seem to be read correctly or at all. Even though there is content when opening the files individually, when attempting to examine their co ...

Illustration of a D3 graph demo

I'm currently working on modifying a d3.js graph example originally created by Mike Bostock. My goal is to replace the d3.csv method with d3.json. I made adjustments to parts of the original code, but unfortunately, my graph has disappeared without an ...