Create a new array in JavaScript by comparing and finding the differences between two existing arrays

I have two arrays - array1 and array2. I want to compare both arrays and create a new array (array3) with values that are unique to array1.

For example,

'mob2', 'pin', 'address2', 'city'
are present in array1 but not in array2. I want to extract these keys and values into array3.

let array3 = [];
let array1 = {
    'fname': 'test text',
    'lname': 'test text',
    'pin': 856,
    'address1': 'test text',
    'address2':'test text',
    'city': 'test text',
    'mob1': 35343434343,
    'mob2': 34343434343
};
let array2 = ['fname','lname','mob1','address1'];

Expected Output:

array3['mob2'] = 34343434343;
array3['pin'] = 856;
array3['address2'] = 'test text';
array3['city'] = 'test text';

Answer №1

To start, gather all the keys from the initial object and store them in an array

['fname', 'lname', 'pin', ...] // keys from `obj`

Next, utilize .filter() on this array to filter out any keys that are present in the arr of keys to be excluded. This will result in an array of keys to keep, which can then be transformed into an array of [key, value] pairs. With this key-value pair array, you can then use Object.fromEntries() to generate your final object:

const obj = {
  'fname': 'test text',
  'lname': 'test text',
  'pin': 856,
  'address1': 'test text',
  'address2': 'test text',
  'city': 'test text',
  'mob1': 35343434343,
  'mob2': 34343434343
};
const arr = ['fname', 'lname', 'mob1', 'address1']; // keys to exclude

const keys = Object.keys(obj).filter(key => !arr.includes(key));
const res = Object.fromEntries(keys.map(key => [key, obj[key]]));
console.log(res);

If there are a significant number of keys to exclude, it is advisable to create a Set first and then utilize .has() instead of .includes() for efficient lookup within the .filter() callback:

const obj = {
  'fname': 'test text',
  'lname': 'test text',
  'pin': 856,
  'address1': 'test text',
  'address2': 'test text',
  'city': 'test text',
  'mob1': 35343434343,
  'mob2': 34343434343
};
const set = new Set(['fname', 'lname', 'mob1', 'address1']); // keys to exclude

const keys = Object.keys(obj).filter(key => !set.has(key));
const res = Object.fromEntries(keys.map(key => [key, obj[key]]));
console.log(res);

Lastly, in case the keys in array2 are fixed, you can make use of destructuring to extract the keys you wish to exclude, and then utilize the rest pattern ... to get an object without those specific keys. However, this method only works with static keys:

const obj = { 'fname': 'test text', 'lname': 'test text', 'pin': 856, 'address1': 'test text', 'address2': 'test text', 'city': 'test text', 'mob1': 35343434343, 'mob2': 34343434343 };

const {fname, lname, mob1, address1, ...res} = obj;
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

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

Creating a carousel of cards using JavaScript, CSS, and HTML

Here is a visual reference of what I'm attempting to achieve: https://i.stack.imgur.com/EoQYV.png I've been working on creating a carousel with cards, but I'm struggling to synchronize the button indicators with card advancement when clicke ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Is there a way to utilize variables from a source XML file to establish points on an SVG polygon?

I've been struggling to figure out if it's possible to dynamically set points on an SVG polygon using variables that are defined by an XML document which is constantly changing. All I want is to set the path like this: var polygonToUse = window. ...

Tips for incorporating external routes into the routes index file

I am currently dealing with a users.js and an index.js file. users.js const express = require('express'); const router = express.Router(); const {catchErrors} = require('../handlers/errorHandlers'); const authController = require(&ap ...

Watchman encountered an error upon initialization

Hi there, I'm encountering an error when trying to start my app with 'react-native start'. Can anyone provide guidance on how to resolve this issue? I attempted changing the permissions of the watchman folder and project folder using chmod - ...

Removing dynamic input fields with VueJS

Need some help with deleting fields in Vue. Managed to get them to render, but not sure how to remove them. I added an index option in the v-for directives, but now I'm stuck. Any suggestions would be appreciated! If you want to see my code in action ...

How to iterate through a Vue data object using forEach loop

I am currently working with a variable in my data: data: function () { return { myVariable: false, } } I'm trying to figure out how to access this variable within a looping function, like the example below: anArray.forEach(functi ...

Is it permissible to use Aloha editor GPL v.2 on a business website?

While researching the licensing of Aloha Editor, I came across some confusing information. I found a reference to another editor under LGPL: However, I couldn't find a clear answer on whether I can use Aloha JS code on a commercial website with GPL v ...

Arrange images in a fluid manner around other images

Check out the website I'm currently working on: metroweb.tk I'm in the process of designing a website that mimics the Windows 8 metro UI. However, I've encountered an issue with larger app icons such as notes and clocks sticking out. Is the ...

Constantly showing false values in AngularJS Firebase array objects

Encountering an issue with retrieving data from Firebase. When viewing console.log($scope.statusbaca), it shows 2 queries, true and false. However, in the app it only displays false. Apologies for any language barriers as English is not my first language. ...

AngularJS can easily interpret and extract information from HTML code

As an example, I have dynamically generated HTML on my webpage like this: <ul> <li>Country</li> <li>State</li> <li>City</li> </ul> I am looking to send this information to the database after clicking a b ...

What is the best way to transmit JSON data to a Web API?

As I work on developing a website with web API integration, I encountered an issue while trying to send JSON data to my controller. Multiple actions were found that match the request: Post on type AuctionWebsiteASP.Controllers.MovesController readDatab ...

Accessing Struts2 tag attributes with JavaScript

Currently, I am using struts2 with jsp. Within the JSP file, there is a table with several rows of data. To display the row data in the table, iterators are being used. Each row includes a button that allows the user to update the row's data, such as ...

Personalize the loading bar using JavaScript

Currently, I am utilizing a basic progress bar from Bootstrap. However, I have the desire to design a custom progress bar similar to this: Unfortunately, I am uncertain about how to create such a unique progress bar. Perhaps there is an existing JavaScri ...

Looking for a bootstrap table code that includes checkboxes and a save button, so that when the save button is clicked, it

Seeking a Bootstrap table code that includes row checkboxes. When the save button is clicked, it should return the selected checkbox rows. ...

Navigate through intricate JSON structure

Struggling with a highly complex JSON object, I am trying to list out all the properties and keys exactly as they are. While I have grasped the concept, I am having trouble with the execution. Every time the object contains another object, I need to call ...

Establish a table containing rows derived from an object

I am currently dealing with a challenge in creating a table that contains an array of nested objects. The array I have follows this schema: array = [ { id: 'Column1', rows: { row1: 'A', row2 ...

A quicker method for setting the emitted value to data

Is there a way to pass data from child to parent without creating a method for assigning the value? I want to be able to assign it directly in the template. This is my current code: Child <h1 @click="$emit('title', 'Home')&quo ...

Difficulty in transmitting two boolean values using ajax and setTimeout()

I am working on two functions that are supposed to send either 0 or 1 to a PHP page using AJAX. When a key is pressed on the keyboard, the function that sends 1 should start, followed by the second function that sends 0 three seconds later using setTimeout ...