Skip to content

Instantly share code, notes, and snippets.

@bhatmand
Created November 25, 2020 12:48
Show Gist options
  • Save bhatmand/35ff36d9805a66daed88197790e1f5dd to your computer and use it in GitHub Desktop.
Save bhatmand/35ff36d9805a66daed88197790e1f5dd to your computer and use it in GitHub Desktop.
Given two arrays, find common items in both arrays.
// ------------------------------------------------
// question: Given two arrays, find common items in both arrays.
var a = [ 1,2,13,11,6,7,4, 8,9,10]
var b = [ 2,4,5,11,13 ]
// ------------------------------------------------
// ------------------------------------------------
// solution: compare each item of the array containing least items, with the other array, and return the common ones.
var a = [ 1,2,13,11,6,7,4,8,9,10 ];
var b = [ 2,4,5,11,13 ];
// make smallest array "a" and the other "b"
var [a, b] = a.length < b.length ? [a, b] : [b, a];
// filter items from array "a", which exist in the array "b"
var c = a.filter(item => b.includes(item));
// array "c" contains common items
console.table(c);
// ------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment