Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active March 2, 2023 06:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/13fc480ce8f2c7a9b65950aeb31c27a1 to your computer and use it in GitHub Desktop.
Save dfkaye/13fc480ce8f2c7a9b65950aeb31c27a1 to your computer and use it in GitHub Desktop.
intersections from more than two arrays
// 2 March 2023
// intersections from more than two arrays
// goaded by https://frontendroom.com/intersection-of-multiple-arrays-in-js/
// works on arrays of values and arrays of objects with a single key;
// not sure I agree with the multiple keys matching output.
// values
var a = ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7"]
var b = ["Item 6", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7"]
var c = ["Item 4", "Item 7", "Item 5", "Item 6", "Item 8", "Item 9"]
var d = ["Item 7", "Item 5", "Item 6", "Item 8", "Item 9", "Item 10"]
var e = ["Item 6", "Item 7", "Item 5", "Item 8", "Item 9", "Item 10"]
// objects
var p = [
{ name: "Item 1" },
{ name: "Item 2" },
{ name: "Item 3" },
{ name: "Item 4" },
{ name: "Item 5" },
{ name: "Item 6" },
{ name: "Item 7" },
]
var q = [
{ name: "Item 6" },
{ name: "Item 3" },
{ name: "Item 4" },
{ name: "Item 5" },
{ name: "Item 6" },
{ name: "Item 7" },
]
var r = [
{ name: "Item 4" },
{ name: "Item 7" },
{ name: "Item 5" },
{ name: "Item 6" },
{ name: "Item 8" },
{ name: "Item 9" },
]
var s = [
{ name: "Item 7" },
{ name: "Item 5" },
{ name: "Item 6" },
{ name: "Item 8" },
{ name: "Item 9" },
{ name: "Item 10" },
]
var t = [
{ name: "Item 6" },
{ name: "Item 7" },
{ name: "Item 5" },
{ name: "Item 8" },
{ name: "Item 9" },
{ name: "Item 10" },
]
function intersection(props, ...rest) {
var [first, rest] = Array.isArray(props)
? [props, rest]
: [rest[0], rest.slice(1)];
var visited = [...first];
Array.isArray(props.keys)
? props.keys.forEach(function(key) {
visited.forEach(function(v, i) {
rest.forEach(function(a) {
if (!a.some(o => v[key] === o[key])) {
visited.splice(i, 1);
}
});
});
})
: visited.forEach(function(v, i) {
rest.forEach(function(a) {
if (!a.some(o => v === o)) {
visited.splice(i, 1);
}
});
});
return visited;
}
console.log(
intersection(a, b, c, d, e)
);
// ['Item 5', 'Item 6', 'Item 7']
console.log(
JSON.stringify(intersection({ keys: ["name"] }, p, q, r, s, t), null, 2)
);
/*
[
{
"name": "Item 5"
},
{
"name": "Item 6"
},
{
"name": "Item 7"
}
]
*/
console.log(
JSON.stringify(
intersection({ keys: ['a', 'b'] },
[{a: 'a', b: 'b', extra: "stuff" },
{a: 'a', b: 'b', c: 'd'},
{a: 'no', b: 'b', c: 'e'},
{a: 'a', b: 'no', c: 'f'},
],
[{a: 'a', b: 'b'}],
[{a: 'a', b: 'b'}],
), null, 2
)
);
/*
[
{
"a": "a",
"b": "b",
"extra": "stuff"
},
{
"a": "a",
"b": "b",
"c": "d"
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment