Ways to compare arrays and merge them into a single array with JavaScript

Here are two arrays of objects:

Object 1:

    [  
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Screenprint Textile"
   }
]

Object 2: [
{
"sku":"30772", "qty":"1" }, {
"position":"Position Arm Left", "tech":"Embroidery" }, {
"position":"Position Chest", "tech":"Screenprint Textile" } ]

Object 2:

[  
   {  
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   }
]

I am looking to compare the object parameters, specifically position and tech, to obtain a final array with matching positions and objects as shown below

Final output:

[  

   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Embroidery"
   }
]

Answer №1

When utilizing lodash, the intersectionWith method comes in handy for finding intersections based on two keys.

const object1 = [
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Chest",
    tech: "Embroidery"
  },
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Chest",
    tech: "Screenprint Textile"
  },
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Arm Left",
    tech: "Embroidery"
  },
  {
    id: "30772",
    posimage: "/b/l/blue-shirt_1_1.jpg",
    position: "Position Arm Left",
    tech: "Screenprint Textile"
  }
];

const object2 = [
  {
    position: "Position Arm Left",
    tech: "Embroidery"
  },
  {
    position: "Position Chest",
    tech: "Screenprint Textile"
  };

const result = _.intersectionWith(
  object1,
  object2,
  (o1, o2) => o1.position === o2.position && o1.tech === o2.tech
);

console.log(result);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad6d5dedbc9d2fa8e948b8d948b8f">[email protected]</a>/lodash.min.js"></script>

Answer №2

Give this a try:

The code is quite straightforward.

UPDATE: This new version of the code has been optimized for efficiency, calculating the length of both arrays and running the loop with fewer objects.

var obj1 =   [  
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Screenprint Textile"
   }
]

var obj2 = [  
   {  
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   }
]

const comparer = (arr1, arr2) => {
  
  let result = [];
  arr1.map((item) => {
    // let toPush = item.hasOwnPropery('id') ? item : second;
    arr2.map(second => {
      if(second.hasOwnProperty('position') &&
          second.hasOwnProperty('tech') &&
          second['position'] === item['position'] &&
          second['tech'] === item['tech']
        ) {
        result.push('id' in item ? item : second);
      }
    })
  })

  return result;
}

let length1 = obj1.length;
let length2 = obj2.length

if(length1 < length2) {
  console.log(comparer(obj2, obj1))
} else if (length2 < length1) {
  console.log(comparer(obj1, obj2))
}

// console.log(comparer(obj2, obj1))

Answer №3

Give this a try, it may be just what you need to find the solution you're looking for.

const items = [  
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "id":"30772",
      "posimage":"/b/l/blue-shirt_1_1.jpg",
      "position":"Position Arm Left",
      "tech":"Screenprint Textile"
   }
];

const filters = [  
   {  
      "position":"Position Arm Left",
      "tech":"Embroidery"
   },
   {  
      "position":"Position Chest",
      "tech":"Screenprint Textile"
   }
];

const matchedItems = items.filter(item => {
  const foundFilter = filters.find(filter => {
    return filter.tech === item.tech && filter.position === item.position;
  });
  return foundFilter;
});

console.log(matchedItems);

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

Creating a Three by Three Grid with HTML and CSS

I have a total of 20 elements to display in a grid view. However, I specifically want a 3x3 grid view, where only 9 elements will be visible in the view window. The remaining elements should be placed on the right side of the window in a scrollable manner. ...

Determine browser compatibility by evaluating the DOM Level

Can we easily determine which browser versions and above are compatible with a certain DOM level? ...

Prevent automatic page reload when the button is clicked

Currently, I am in the process of developing a system for internal use within our company that will enable our service desk team to unlock user accounts and reset passwords. I have successfully implemented the PHP/POST functions and integrated them with t ...

The implementation of SetInterval within nested functions in JavaScript appears to be malfunctioning

I am a beginner in the world of JavaScript and I am currently attempting to incorporate the setInterval method within functions in Js. JavaScript Code: var tar = document.getElementById("sample"); function dataSample(tar) { //setInterval ...

Exploring the world of chained JavaScript Promises for automatic pagination of an API

Dealing with a paged API that requires fetching each page of results automatically has led me to construct a recursive promise chain. Surprisingly, this approach actually gives me the desired output. As I've tried to wrap my head around it, I've ...

merge two structures to create a unified entity

I have been searching in vain, can you please advise me on how to combine these two simple forms into one? I want it to be like a box with a select option and a button. The challenge for me is merging the two different actions, ".asp", into one script fo ...

Is it possible to implement an automatic scrolling functionality in this code snippet?

https://codepen.io/hexagoncircle/pen/jgGxKR?editors=0110 Stumbled upon some interesting code to tinker with and came across this piece. Attempted to search online for solutions, but my grasp on React (or maybe Java?) is close to zero. Tried following guid ...

Error in tabs.onUpdated argument in Firefox WebExtensions

I am currently working on developing a straightforward webExtension for Firefox and I would like to implement tabs.onUpdated with a filter. I found an example on the Mozilla website that I decided to use: const pattern1 = "https://developer.mozilla.org/*" ...

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

Error TS2346: The parameters provided do not match the signature for the d3Service/d3-ng2-service TypeScript function

I am working with an SVG file that includes both rectangular elements and text elements. index.html <svg id="timeline" width="300" height="100"> <g transform="translate(10,10)" class="container" width="280" height="96"> <rect x ...

Can you explain NodeSource in simple terms, and what purpose does it serve?

Not too long ago, I delved into researching how to effectively host a MEAN stack web application on AWS. During my quest for knowledge, I stumbled upon a tutorial that caught my eye. The one I ended up following can be found at https://www.youtube.com/wat ...

Couchbaselite error: Invalid or nonexistent JSON data

I am currently trying to store properties in a Couchbase document within an Android application. These properties include a JSONArray containing multiple JSONObjects. However, when I attempt to use document.putProperties(myProperties), it throws a Couchba ...

My div is currently being concealed by a jQuery script that is hiding all of its

Below is the current code snippet: jQuery(document).ready(function($) { $("ul.accordion-section-content li[id*='layers-builder'] button.add-new-widget").click(function() { $("#available-widgets-list div:not([id*='layers-widget']) ...

What is the process for enabling a Submit button and updating its value following a successful Ajax response within a Django environment?

My current project involves using Django as the web framework. I am in the process of setting up an AWS lab or AWS account. To avoid multiple submissions, I have disabled the Submit button once the user enters information such as lab name, CIDR block, etc. ...

NodeJS: Encountering an issue with retrieving the cart ID - receiving

I am having issues with the cart variable, even though I defined it using await cartsRepo.create({ items: [] });. For some reason, I keep getting undefined when trying to access cart. I suspect that the request is not resolving properly, which might be ca ...

Display a linear list organized in a tree format, showcasing instances where children have multiple parents

I am new to Javascript and programming in general. I am working with a list of "step" objects that have a choice/solution field which references another object in the same list. My goal is to create a tree hierarchy based on this field. [ Below is the arr ...

Retrieving radio button value in Angular 2

Currently, I am attempting to retrieve the radio button value in an Angular 2 project. The radio buttons are defined in index.html as: <input type="radio" id="options1" name="function" value="create"> <input type="radio" id="options2" name="func ...

Different ways to use functions with AngularJS, including the parsley and reset options

Here are two functions I use to reset error messages and form field values: $("#modal_form").parsley().reset();//This only resets error messages, not form field values $("#modal_form")[0].reset();//This only resets form field values, not error messages I ...

"The rotation speed of the CameraHelper in three.js surpasses that of the Perspective

I have a THREE.PerspectiveCamera equipped with a THREE.CameraHelper. cameraLocal = new THREE.PerspectiveCamera(70, 1, 20, 120); scene.add(cameraLocal); cameraLocalHelper = new THREE.CameraHelper(cameraLocal); cameraLocal.add(cameraLocalHelper); However, ...

When a user selects an item from ion-item, a new page should open

Check out the codepen for reference. 1) I'm trying to create a functionality where, upon clicking on an item, a new details page opens up to display information about that specific item. Once on the details page, there should be an "OK" button that, ...