Determine the shared elements between two distinct arrays and create an object that includes these common elements

I am dealing with 2 different arrays of objects

var array1 = [
{id: 1, name:'fruit', rating:5},
{id: 4, name:'vegetable', rating: 3},
{id: 8, name:'meat', rating:1}
];

var array2 = [
{alimentId: 1, quantity: 2},
{alimentId: 4, quantity: 2},
{alimentId: 8, quantity: 4}
] 

and my goal is to create a new array that contains only specific elements from array1 based on certain conditions.

var array = [
    {id: 1, name:'fruit'},
    {id: 4, name:'vegetable'},
]

I need help in filtering out the elements with quantity 2 that match the alimentId with the id. Arrays and object manipulations confuse me at times, any assistance would be greatly appreciated.

Answer №1

After analyzing your issue, I suggest utilizing the code snippet below as a potential solution:

const customFilter = (array1, array2) => {
  return array1.filter(object => {
    const objectToCheck = array2.filter(item => item.productId === object.id);
    return objectToCheck[0].quantity === 2;
  });  
};

In addition, you have the option to input the desired value (2) and the corresponding key name (quantity) as parameters for further customization.

Answer №2

var array1 = [
{id: 1, name:'fruit', rating:5},
{id: 4, name:'vegetable', rating: 3},
{id: 8, name:'meat', rating:1}
];

var array2 = [
{alimentId: 1, quantity: 2},
{alimentId: 4, quantity: 2},
{alimentId: 8, quantity: 4}
] 
       function filter(array1, array2) {
        return array1
         .filter(it => array2 // filtering array1 by array2
           .filter(it => it.quantity === 2) // filtering array2 by field quantity = 2
           .map(it => it.alimentId) // extracting array of alimentId
           .includes(it.id) // checking if array2.alimentId includes array1.id
          )
        }

console.log(filter(array1, array2))

Answer №3

implementing the following function

const find_common_elements = (array1, array2, amount) => {
  let result = []
  array1.forEach(element1 => {
    array2.forEach(element2 => {
      if(element1.id === element2.alimentId && element2.quantity === amount) {
        result.push(element1)
      }
    });
  });

  return result
}

Answer №4

One way to achieve this is by using the reduce method:

var filteredArray = originalArray.reduce((result, value, index) => {
    if (value.id === filterArray[index].alimentId) {
        result = [...result, {id: value.id, name: value.name}];
    }
    return result;
}, []);

Answer №5

const fruits = [
  {id: 1, name:'apple', rating:5},
  {id: 4, name:'carrot', rating: 3},
  {id: 8, name:'beef', rating:1}
];

const groceries = [
  {alimentId: 1, quantity: 2},
  {alimentId: 4, quantity: 2},
  {alimentId: 8, quantity: 4}
]

const commonItems = groceries.filter(item => item.quantity === 2 && fruits.find(el => el.id===item.alimentId));

console.log(commonItems)

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 integration of hapi.js with mysql appears to be experiencing difficulty displaying values on the browser

My attempt to retrieve a list of data from mysql using hapi.js resulted in an error message: Error: method did not return a value, a promise, or throw an error However, I can see the data in my console. [ RowDataPacket { id: 1, code: 'test' ...

Using SOAP in a JavaScript-exclusive setting

I'm looking into utilizing SOAP as the backend services to supply data for my application. My query pertains to the feasibility of implementing this with just a JavaScript framework like Ember or Angular, without utilizing server-side languages such ...

Cookies are mysteriously invisible in the developer console of Safari/Chrome when using the Set-Cookie Header, yet they miraculously appear in server logs

Storing cookies for my web app using the 'Set-Cookie' header response from my python backend has been a challenge. https://i.stack.imgur.com/XMx35.png An ajax call on the client-end to the function is where I run into issues: https://i.stack.im ...

Utilize Babel transpiling specifically for necessary Node modules

My current setup in nextjs is configured to handle ES6 code for IE11. module.exports = { poweredByHeader: false, distDir: "ssr_build", webpack(config) { config.node = { fs: "empty", net: "empty", tls: "empty" } config.plugins = config.plugi ...

numpy/scipy in Python for binning using a vectorized method

Looking to categorize a 2D array (x by y) in Python based on its x value into predefined bins using np.digitize: elements_to_bins = digitize(vals, bins) The input "vals" is structured as a 2D array: vals = array([[1, v1], [2, v2], ...]). Once the binn ...

The blur() function in -webkit-filter does not seem to function properly in Vue.js

I'm having trouble implementing the -webkit-filter: blur() property. I tried using "filter" instead, but it still isn't working. Could this be a limitation of Vue.js or are there any other solutions available? <template> <div class=&qu ...

Adding a Fictitious Pair to a JavaScript Object Literal

When I work with object literals in JavaScript, I often encounter syntax errors when adding a new label / value pair without including the trailing comma. This can be frustrating as it's easy to forget to include the necessary delimiter. .draggable({ ...

What causes the source code of a website to change when accessed from various browsers?

When analyzing the source code of bartzmall.pk using various browsers, it reveals different classes being added to the html tag for each browser. For Firefox: <html class="firefox firefox53 otherClasses"> For Chrome: <html class="webkit chrome ...

Step-by-step guide to customizing the theme in Nuxt using Vuetify

I am new to using Nuxt and Vue, and I am attempting to switch the color theme from dark to light. The project was created using Nuxt CLI, and these are the versions I am using: "dependencies": { "core-js": "^3.8.3", "nuxt ...

The connection between the layout of dropdown menus and the way data is handled in forms

I have discovered three different methods for creating dropdowns that can be used in forms: 1) Utilizing HTML with "form-dedicated" attributes such as select and option value="" 2) Implementing the Bootstrap framework with div classes like "dropdown", Butt ...

Looking to adjust the title font size when exporting DataTable to Excel?

Would like to customize the title of an excel file exported from Datatable. I attempted to implement a solution found on a stackoverflow post, but it ended up applying the customization to the entire sheet. $("#datatable").DataTable({ ...

Tracking the number of images and adjusting the counter as the user scrolls

I am working on a project where I have a series of images displayed in a column. I would like to add a dynamic counter to indicate which image is currently in focus based on the scroll position. Feel free to check out the demo <div class="counter"> ...

Tips on showcasing the elements within a div container using flexbox

Seeking advice on positioning items/cards using flexbox in my initial react app. The issue lies with the div within my card component where applying display: flex; turns every card into a block (column-like) structure, flexing only the content within each ...

Is there a way to make the button text bold before deleting it post clicking on an alert message?

While testing my sequence in IE, I noticed that it appeared correctly, but in Chrome, the button text was not showing up as bold. Instead, only the alert message was displayed, and the button itself was removed. Upon further investigation using Chrome&apo ...

Audio in A-Frame does not function properly when in VR mode

My friend and I are collaborating on a small project involving a VR simulation that requires audio instructions. While everything functions smoothly in the web version and even on mobile devices, we encountered an issue when switching to VR mode on mobile ...

Updating v-model with inputs is proving to be a difficult task

Creating object instances as responses can be done like this: <el-input :id="'question_' + question.id" v-model="answers[question.id]"></el-input> When entering data into these inputs, the output will look something like this: Answ ...

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

Exploring nested JSON through recursive iteration in JavaScript

Consider this JSON data containing comments that are fetched via AJAX call: json = 'comments': [ {'id':1,'parent':0}, {'id':2,'parent':1}, {'id':3,'parent':2}, {'id&apos ...

Expanding Java Classes and Replacing Methods with Multiple Parameters in ES4X/Graal

I am currently facing a challenge in my JavaScript project using ES4X/Graal, where I need to extend a Java class. This Java class has methods with overloaded parameters that I must override. While I understand how to call a specific Java method by specifyi ...

Preventing the "save" button from being enabled until a change has been made to at least one input field

I have a page with approximately 20 input fields, along with save and register buttons. Is there a way to activate the "save" button only when a change has been made in at least one of the fields? ...