user15512721
user15512721

Reputation: 3

Compare two arrays and make the another array with difference in javascript

I have the below type of two arrays, I want to check both array(array1 and array2) and create another array(array3), which has a value, which are not available into array1.

For ex - 'mob2', 'pin', 'address2', 'city' are available in array1 but not in array2. I want to those array keys and values in 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';

Upvotes: 0

Views: 125

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

You can first get all the keys from your first object into an array

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

You can then use .filter() on this array to remove any key values that appear in your arr of keys to exclude. This will give you an array of keys to keep, which you can map over to create an array of [key, value] pairs. This key-value pair array can then be used in a call to Object.fromEntries(), which will build your resulting object for you:

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 the number of keys to exclude is large, consider making a Set first, and then using .has() instead of .includes(). This will allow for efficient lookup within your .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, if the keys in array2 are static, you use destructuring to pull out the keys you want to exclude, and then use the rest pattern ... to obtain an object without those keys. This only works with static keys though:

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);

Upvotes: 2

Related Questions