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 :: get file extention js 
Javascript :: forach loop in javascript 
Javascript :: add bootstrap to angular 13 
Javascript :: Reverse pyramid star pattern in JavaScript 
Javascript :: prime number js 
Javascript :: react parameter value from query string 
Javascript :: js convert truthy 
Javascript :: javascript html string to plain text 
Javascript :: axios send post data 
Javascript :: empty input of clone jquery 
Javascript :: how to use static files in express with ejs 
Javascript :: js first letter to uppercase 
Javascript :: Cast to ObjectId failed for value 
Javascript :: disable button click jquery 
Javascript :: Remove duplicate items form array using reduce() method. 
Javascript :: alpine in laravel mix 
Javascript :: how to use media queries in emotion 
Javascript :: like knex 
Javascript :: json with multiple objects 
Javascript :: js toggle class 
Javascript :: put 0 in front of month number javascript 
Javascript :: js find longest word in string function 
Javascript :: async in useeffect 
Javascript :: regex not contain 
Javascript :: how to control playback speed in javascript 
Javascript :: js throw custom error 
Javascript :: jquery reload iframe 
Javascript :: how to fix header on scroll 
Javascript :: js weakset 
Javascript :: get date js 
ADD CONTENT
Topic
Content
Source link
Name
6+3 =