Last active
December 12, 2018 22:31
-
-
Save LB-Digital/20b1c8b77910aa2eabb36e08008859d7 to your computer and use it in GitHub Desktop.
Find the intersection between two JS arrays of objects, based on an object property (using 'filter' and 'map').
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Find the intersection between two JS arrays of objects | |
* finds based on an object property (using 'filter' and 'map') | |
*/ | |
products = [ // an array of products | |
{reference:'LOWP8F7H', name:'Nike Blazer', price:120, category:1}, | |
{reference:'3PFH3LDP', name:'Nike Kyrie', price:340, category:1}, | |
{reference:'FGH4P40K', NAME:'Nike Bomber', price:70, category:0} | |
]; | |
resultProducts = [ // a second array of products | |
{reference:'ANFHO2f3', name:'Adidas NMD', price:90, category:1}, | |
{reference:'LOWP8F7H', name:'Nike Blazer', price:120, category:1}, | |
{reference:'3PFH3LDP', name:'Nike Kyrie', price:340, category:1} | |
]; | |
// finding the intersection between them | |
var intersection = products.filter((product, pos, arr)=>{ // loop through each product | |
var resProdRefs = resultProducts.map(mapObj => mapObj.reference); // get all refs of the resultProducts | |
if (resProdRefs.indexOf(product.reference) > -1) return true; // if the loop product ref is in resultProduct refs | |
return false; // item doesn't intersect | |
}); | |
console.log(intersection); // returns the 2 intersecting items | |
// The above code can even be shortened to the following... | |
var intersection = products.filter(product=>{ | |
return resultProducts.map(mapObj => mapObj.reference).indexOf(product.reference) > -1; | |
}); | |
console.log(intersection); //returns same 2 intersecting items |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment