Discovering the shared elements within an array of objects using Javascript

My data is structured in the following way:

const Items = [{"Name":"type1","Options":[1,2,5]},{"Name":"type2","Options":[1,2]},{"Name":"type1","Options":[2,5]}];

Although I am new to javascript, I am trying to identify the common options associated with each type name.

The number of elements in the Items array can vary. It might be 40 for example.

If we consider the above data, my expected output would look like this:

CommonOptions = [{"Name":"type1","Options":[2,5]},{"Name":"type2","Options":[1,2]}];

This is because 2 and 5 are common to all items with name type1, while 1 and 2 are common among items with name type2. However, I am unsure about how to correctly access this data.

I have made progress so far. Any guidance on the right direction would be greatly appreciated.

const Items = [{
  "Name": "type1",
  "Options": [1, 2, 5]
}, {
  "Name": "type2",
  "Options": [1, 2]
}, {
  "Name": "type1",
  "Options": [2, 5]
}];

let CommonOptions = [];
CommonOptions.push(Items[0]);

for (let i = 1, iLen = Items.length - 1; i < iLen; i++) {
  for (let j = 0, cLen = CommonOptions.length; j < cLen; j++) {

    if (CommonOptions[j].Name.includes(Items[i].Name)) {
      CommonOptions.push(Items[i]);
    } else {
      // Check Options array for common values
    }
  }
}
console.log(CommonOptions);

Answer №1

To handle objects with the same name, you can utilize a hash table and filter out common elements from the Options array.

var items = [{ Name: "type1", Options: [1, 2, 5] }, { Name: "type2", Options: [1, 2] }, { Name: "type1", Options: [2, 5] }],
    hash = Object.create(null),
    common = items.reduce(function (result, obj) {
        if (hash[obj.Name]) {
            hash[obj.Name].Options = hash[obj.Name].Options.filter(function (value) {
                return obj.Options.indexOf(value) !== -1;
            });
        } else {
            hash[obj.Name] = { Name: obj.Name, Options: obj.Options.slice() };
            result.push(hash[obj.Name]);
        }
        return result;
    }, []);

console.log(common);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To effectively manage the array state for each name and apply filtering as needed, it's crucial to maintain a separate instance of the array for each unique name.

const Items = [{"Name":"type1","Options":[1,2,5]},{"Name":"type2","Options":[1,2]},{"Name":"type1","Options":[2,5]}];

const m = Items.reduce((m, o) => {
  const a = m.get(o.Name);
  return m.set(o.Name, a ? a.filter(n => o.Options.includes(n)) : o.Options);
}, new Map());

const res = Array.from(m.entries(), ([Name, Options]) => ({Name, Options}));
console.log(res);

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

Utilizing Vue.js to add functionality for navigation buttons allowing users to move between survey questions

In my Vue.js component, I've written code to show survey questions in a mobile app for users. Here is a snippet of the code: <div class="col-12 p-0" v-for="( i, index ) in questions" :key="i"> <p cl ...

Issue with data transfer in Angular 6 routes

I created an application that showcases a table of different cars: Here is my code snippet for the car component: Carcomponent.html <tbody> <tr *ngFor="let car of allCars; index as carId" \> <td [routerLink]="[&apos ...

Retrieving and securely storing information using fetch() on authenticated REST services

Currently, I have successfully set up a React application that communicates with a REST backend which is built using Python and Flask. The specific functionality I have achieved involves downloading data from a database and saving it as a CSV file through ...

How can I identify when a CSS transition on a particular element has ended if there are several transitions occurring simultaneously?

In my coding, I have been utilizing the following method to identify when a CSS3 transition has finished: CACHE.previewControlWrap.css({ 'bottom':'-217px' }).one('webkitTransitionEnd transitionend m ...

Is there a clash between jquery_ujs and Kaminari AJAX functionality in Rails 4?

After some investigation, it seems that there is a conflict between jquery_ujs and Kaminari's AJAX support in my Rails 4 application. Within my application.js file, I have included the following: //= require jquery //= require jquery_ujs //= require ...

Incorporating an AngularJs App into Joomla: A Step-by-

As someone who is currently learning both Angular and Joomla, I am curious about the possibility of integrating an Angular JS Application within Joomla. While Joomla is known for its ease in creating articles and managing content through the admin panel, i ...

Using VUE.JS to trigger a function that applies discounts prior to form submission

Before submitting my form with Axios, I am in need of applying specific discounts to each item within campaign.items. To achieve this, a functional method has been created: applyDiscount(price) { return price - (this.totalDiscount * price) }, Pri ...

jQuery file uploader only transmitting a single chunk

Currently, I am integrating the jQuery file uploader into my Django application. I am encountering an issue where Django is only receiving one chunk of my large file. Initially, I suspected a problem with my UploadFileHandler; however, upon logging the ch ...

Steps for refreshing the content within a div without having to reload the entire page following an ajax request

I am trying to achieve the task of reloading the content of a specific div on a webpage without refreshing the entire page. My goal is to reload the div after uploading a photo so that the newly uploaded photo can be displayed from the database. However, t ...

Unable to populate an HTML table with JSON data

Can you assist me in populating a table using data from a JSON response? [ { "id": 1, "firstName": "James", "nickNames": [ {} ] }, { "id": 2, "firstName": "Linda", "nickNames": [ { "id": 2, "na ...

Building a chat console resembling IRC using JavaScript

I am a novice in HTML and JavaScript. I am currently working on creating a simple program that takes input from the user via the command line and displays it in a large console window. However, when I enter a simple text, nothing is displayed in the box. D ...

Enforce linting rules for webpack aliases using ESLint

I am currently working with a webpack configuration file that functions as a factory (react-universally boilerplate). In this setup, I have included an resolve option structured like so: resolve: { // These extensions are attempted when resolving a ...

Changing a JavaScript array by including a numerical value

Here is my original dataset... [{ month: 'Jan', cat: 'A', val: 20 },{ month: 'Jan', cat: 'B',' val: 5 },{ month: 'Jan', cat: &ap ...

Is it possible to pass image data response from jQuery .ajax into a new AJAX call?

Currently, I am attempting to combine the ImageOptim API with the OCR.space API. Both APIs are exceptional, and I cannot recommend them highly enough! However, a challenge arises as the OCR API only accepts images under 1mb or 2600x2600 px in the free tier ...

Why is it that every time I install an npm package, it triggers a re-installation of all

Whenever I attempt to install a new package using npm, I face a frustrating problem where it also starts to install all of my other packages, leading to potential breakage and the need to reinstall my node modules. I am puzzled by this behavior and unsure ...

Ways to extract random elements from a variety of arrays

I'm looking for the best way to extract data from multiple arrays. Currently, I have: $array1 = ['A', 'B', 'C', 'D', 'E']; $array2 = ['Q', 'W', 'P', 'R', &apos ...

Having trouble viewing the page of a new package you published on the NPM Website?

Today, I officially released an NPM package called jhp-serve. It can be easily installed using npm install or run with npx. You can even find it in the search results here: https://www.npmjs.com/search?q=jhp. However, when attempting to view its page by cl ...

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

Navigating Three.js coordinate systems

While working with vectors in three.js, I noticed that the axes seem to be mixed up. It's confusing because Y is the vertical axis, but X and Z appear "mirrored" causing objects to only look right when viewed upside-down. How can this issue be resolv ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...