Last active
August 9, 2021 21:23
-
-
Save monkpit/290eff31aa273c41ae8ad0c7e9577319 to your computer and use it in GitHub Desktop.
Cross product of 2 javascript arrays
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
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)); |
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
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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])
toif (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):