Skip to content

Instantly share code, notes, and snippets.

@monkpit
Last active August 9, 2021 21:23
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 monkpit/290eff31aa273c41ae8ad0c7e9577319 to your computer and use it in GitHub Desktop.
Save monkpit/290eff31aa273c41ae8ad0c7e9577319 to your computer and use it in GitHub Desktop.
Cross product of 2 javascript arrays
const {equals, flatten, join, map, pipe, unnest, xprod} = require('ramda');
const xprod2 = require('./xprod.js');
const urls = [
'stackexchange.com',
'askubuntu.com',
'superuser.com'
];
const filters = [
'###sidebar',
'###left-sidebar',
'###overlay-header',
'##.site-footer--container',
'##.js-review-button',
'##.top-bar'
]
const createFilters = pipe(xprod, map(join('')), unnest);
const createFilters2 = pipe(xprod2, map(join('')), unnest);
const res = createFilters(urls, filters);
const res2 = createFilters2(urls, filters);
console.dir(res);
console.dir(res2);
require('assert')(equals(res, res2));
// returns an array with pairs representing the cross product of the 2 arrays
// xprod([1,2,3], [4,5,6]) === [[1,4],[2,5],[3,6]];
export default (a, b) => {
var result = [];
for (const i of a) {
for (const j of b) {
result.push([i, j]);
}
}
return result;
}
@monkpit
Copy link
Author

monkpit commented Aug 9, 2021

To dedupe the results (i.e., [1,2,3] X [1,2,3] and you do not want [1,1] in the results, you can do it a few different ways:

change result.push([i, j]) to if (i !== j) result.push([i, j])

Or

Leave the implementation as-is and just filter the result (if it is small enough to iterate over every pair without too much performance loss):

const result = xprod([1,2,3],[1,2,3]);
const dedupedResult = xprod.filter([a,b] => a === b);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment