Discovering the point of overlap between two arrays of objects featuring variable properties

There are two arrays of objects in my code, each with dynamic keys whose names I am unsure of. For example:

array1: [
  {
    level1: 'Shoes',
  }
]

array2: [
  {
    level1: 'Shoes',
    level2: 'Sneakers',
  },
]

I am looking for a way to find the intersection between array1 and array2 without knowing the key names beforehand. The lodash _.intersectionBy method won't work in this case due to the uncertainty of key names in array1.

The expected result should look like [{ level1: 'Shoes' }]. Any suggestions on how to tackle this problem are highly appreciated!

Thank you very much!

Answer №1

For a comprehensive comparison with every index, you can utilize the following method:

const hierarchy1 = [{
  level1: 'Shoes',
  level3: "xyz"
}]

const hierarchy2 = [{
  level1: 'Shoes',
  level2: 'Sneakers',
}, {
  level3: "xyz"
}]

function intersection(arr1, arr2) {
  let final = []
  // iterate over the first array
  for (let i = 0; i < arr1.length; i++) {
    let element = arr1[i]
    let temp = {}
    
    // loop through all indexes of the second array
    for (let data of arr2) {
      // check each key in data for any intersections
      Object.keys(data).forEach(key => {
        if (data[key] === element[key] && key in element) {
          temp[key] = element[key]
        }
      })
    }
    // push any found intersection into the final array
    if (Object.keys(temp).length) {
      final.push(temp)
    }
  }
  return final
}

console.log(intersection(hierarchy1, hierarchy2))

An enhanced approach involves pre-calculations to optimize the process. You can consolidate all values for a specific key and efficiently verify the presence of a particular value for the given key during iteration.

const hierarchy1 = [{
  level1: 'Shoes',
  level3: "xyz"
},{level2: "abc"}]

const hierarchy2 = [{
  level1: 'Shoes',
  level2: 'Sneakers',
}, {
  level3: "xyz",
  level2: "abc"
}]

function intersection(arr1, arr2) {
  let final = []
  let map = {}
  for(let data of arr2){
    Object.keys(data).forEach(key => {
      map[key] = map[key] || new Set()
      map[key].add(data[key])
    })
  }
  // iterate over the first array
  for (let i = 0; i < arr1.length; i++) {
    let element = arr1[i]
    let temp = {}
    Object.keys(element).forEach(key => {
      if (key in map && map[key].has(element[key])) {
         temp[key] = element[key]
      }
    })
    // push any found intersection into the final array
    if (Object.keys(temp).length) {
      final.push(temp)
    }
  }
  return final
}

console.log(intersection(hierarchy1, hierarchy2))

If your focus is only on comparing corresponding indexes or both arrays, this streamlined method could be implemented:

const hierarchy1 = [{
  level1: 'Shoes',
}]

const hierarchy2 = [{
  level1: 'Shoes',
  level2: 'Sneakers',
},]

function intersection(arr1,arr2){
  let final = []
  for(let i=0; i<arr1.length; i++){
    let element = arr1[i]
    let temp = {}
    Object.keys(element).forEach(key => {
       if(key in arr2[i] && arr2[i][key] === element[key]){
         temp[key] = element[key]
       }
    })
    if(Object.keys(temp).length){
      final.push(temp)
    }
  }
  return final
}

console.log(intersection(hierarchy1,hierarchy2))

Answer №2

This method can be utilized to slightly adjust the shape of the data.

let combined = [...array1, ...array2].map(entry=> Object.entries(entry)).flat()
/*
[
  [ 'type', 'Fruit' ],
  [ 'type', 'Vegetable' ],
  [ 'category', 'Apple' ]
]
*/

Subsequently, you can transform it into your desired format

combined.reduce((accumulator,[key,value])=>({
     ...accumulator, 
    [key]: accumulator[key]?accumulator[key]+1:1
  }),{})

/*
{ type: 2, category: 1 }
*/

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

What is the process for releasing Dynamic Arrays?

Here is the code snippet I am currently dealing with... while(temp[i]!=0){ while(temp[i]!=3){ FrameBuffer[a]=temp[i]; i++; a++; } FrameBuffer[a]=temp[i]; printf(" Framebuffer: %s ", FrameBuffer); result=layer1(F ...

Sorting objects in Angular using ng-options

I am working with an object that has the following structure: { 3019: 'Javascript', 3046: 'Css' } After that, I display this object in a select element like this: <select ng-model="langChoosed" ng-options="key as val ...

Tips for parsing a tsp library file with JavaScript

Looking for assistance with a tsp library file in JavaScript. The specific file, named file1.tsp, contains the following data: NAME: a280 COMMENT: drilling problem (Ludwig) TYPE: TSP DIMENSION: 280 EDGE_WEIGHT_TYPE: EUC_2D NODE_COORD_SECTION 1 288 149 ...

Enhance Select Dropdown in AngularJS with Grouping and Default Selection

I am facing an issue with a form that includes a SELECT element. I have successfully loaded the possible values in my controller from a function that retrieves data from a database and groups the options by a group name. Although the list of options is lo ...

multer - the file uploaded by the request is not defined

I've been working on an app with Node, Express, and multer for image uploads. However, after submitting the form, req.file is coming up as undefined. I've spent hours trying to troubleshoot this issue but haven't been able to pinpoint the pr ...

AJAX Communication Issue: Data not transferring from client-side to backend in C# MVC 5 via HTTP

I've encountered a problem with sending data from a JavaScript frontend to my C# MVC 5 backend. Despite debugging the code in Visual Studio, the data I'm trying to pass always ends up as null. Below is my front end code: var file = $("#my-file" ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...

Display HTML tags on an HTML page using TypeScript

In my angular application, I encountered an issue where I needed to call one component inside another component. Initially, I was able to achieve this by simply using the second component's selector in the HTML of the first component: html: <div&g ...

What is the best way to clear an InputField when the user switches the RadioField selection?

I am currently using shadcn and react-hook-form. In my form, I have a Radiobutton that triggers an additional input field if the user selects yes. The issue I'm facing is when the user selects yes, fills out the extra input field, and then changes the ...

Access your own data, shared data, or designated data with Firebase rules

Seeking guidance on implementing firebase rules and queries for Firestore in a Vue.js application. Requirement: User must be authenticated User can read/write their own data entries User can read data with "visibility" field set to "public" User can rea ...

The function L.featureGroup.subGroup() is a powerful tool provided by Leaflet and Cart

I'm struggling with getting the subgroups to function correctly. The clusters display, but when I deactivate layers, the clusters do not update accordingly. Moreover, activating a layer turns on all underlying points. How can I ensure that the subgrou ...

Automatically updating content dynamically loaded through JSON

Currently, I have a small jQuery script that fetches the last song I listened to from last.fm. Here is the code: $.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=paul_r_schaefer&api_key=0f680404e39c821cac34008cc4d ...

Conceal the element if the output of express is void

I am currently developing an app using nodejs and express. I am retrieving JSON data from an endpoint and displaying it on the page based on the values received. The issue I am facing is that if I receive a null or undefined value from the JSON data, how ...

Tips for Removing Leading and Trailing Spaces from a String Array in C#

Is there a way to eliminate all white spaces and empty strings from the beginning and end of an array in C# without converting it into a string? I have attempted a solution, but I am seeking a more efficient method rather than settling for just a working ...

What is the best way to exclude the bottom four rows when sorting with MatSort?

Is there a way for me to keep the last four rows fixed when sorting the table based on the column header? Here is an image of the table: table image <table mat-table [dataSource]="dataSourceMD" matSort (matSortChange)="getRowMaximoTable( ...

What are the steps to run a webpack project without relying on webpack-dev-server?

I've been working on hosting my project on GitHub pages by creating a /doc file and placing all my HTML, CSS, and JS there. If you're interested, you can check out my project here: https://github.com/mattfrancis888/the_movie_db The only way I&a ...

Using jQuery or JavaScript to adjust the bottom margin

Looking to Add Bottom Margin for Selection Box I have attempted the following CSS: #Selection { margin-bottom:23px; } Unfortunately, this method did not work for me. Is there a way to achieve this using JavaScript or jQuery? View Example on JsFiddle S ...

Strangely, the quirks of the .hover() function on iOS

I'm finding it puzzling why .hover() is acting differently on iOS. On my desktop, I have a portfolio gallery with images that link to individual pages of my work. When hovering over an image, it slightly fades and a title animates in. However, when I ...

Is it possible to perform a binary search on a collection of objects in an array?

As I delve into the world of searching and sorting algorithms, I've encountered a challenge with implementing a binary search on an array of customer objects. This particular array is sorted by both first and last name. The objective here is to locat ...

The JSON field is missing from the GET response in mongoose

I am dealing with a JSON document (found in mongolab): { "_id": { "$oid": "566e8673eb862d165fef7171" }, "street": "Dizingof", "buildingNumber": 33, "apartmentNumber": 63, "beds": 3, "owner": { "_id": { ...