Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

find intersection between two object arrays javascript

// Generic helper function that can be used for the three operations:        
const operation = (list1, list2, isUnion = false) =>
    list1.filter(
        (set => a => isUnion === set.has(a.userId))(new Set(list2.map(b => b.userId)))
    );

// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
      inFirstOnly = operation,
      inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);

// Sample data
const list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
const list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2));
Comment

PREVIOUS NEXT
Code Example
Javascript :: jest expect async function to throw error 
Javascript :: js letters alphabet array 
Javascript :: Javascript detect mobile browser 
Javascript :: javascript get string between two characters 
Javascript :: js code to generate random base64 code 
Javascript :: get actual time jquery 
Javascript :: javascript css link append 
Javascript :: each element in array jquery 
Javascript :: how to open a new tab in react 
Javascript :: jquery ajax post form 
Javascript :: react native navigation hide navbar 
Javascript :: split string by uppercase javascript 
Javascript :: jquery select by data attribute 
Javascript :: vue.js use scss in balise style 
Javascript :: Solving environment: failed with repodata from current_repodata.json, will retry with next repodata source. 
Javascript :: RegExp validation for password explained 
Javascript :: conditionally add a property to an object 
Javascript :: separate digits in javascript 
Javascript :: Math.random javascript double 
Javascript :: confirm delete message in jquery 
Javascript :: how to use session using javascript 
Javascript :: regex pattern for mobile number 
Javascript :: clearinterval in useeffect 
Javascript :: onchange select dropdown jquery 
Javascript :: free json hosting 
Javascript :: how to let a function execute after 5 seconds javascript 
Javascript :: phone number regex angular 
Javascript :: random generating api for quotes 
Javascript :: javascript get domain name from string 
Javascript :: running a sails js app 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =