JSFiddle - React, Tailwind, and code Playground
JavaScript
var arr = [
{"a": "x"},
{"b": "0"},
{"c": "k"},
{"a": "nm"},
{"b": "765"},
{"ab": "i"},
{"bc": "x"},
{"ab": "4"},
{"abc": "L"},
{"dummy": "asdf"}
];
// Utility function to be used in the cartessian product
function flatten(arr) {
return arr.reduce(function (memo, el) {
return memo.concat(el);
}, []);
}
// Utility function to be used in the cartessian product
function unique(arr) {
return Object.keys(arr.reduce(function (memo, el) {
return (memo[el] = 1) && memo;
}, {}));
}
// It'll prepare the output in the expected way
function getObjArr(key, val, processedObj) {
var set = function (key, val, obj) {
return (obj[key] = val) && obj;
};
// The cartessian product is over so we can put the 'special case' in an object form so that we can get the expected output.
return val !== 'repeated' ? [set(key, val, {})] : processedObj[key].reduce(function (memo, val) {
return memo.concat(set(key, val, {}));
}, []);
}
// This is the main function. It'll make the cartessian product.
var cartessianProdModified = (function (arr) {
// Tweak the data model in order to have a set (key: array of values)
var processedObj = arr.reduce(function (memo, obj) {
var firstKey = Object.keys(obj)[0];
return (memo[firstKey] = (memo[firstKey] || []).concat(obj[firstKey])) && memo;
}, {});
// Return a function that will perform the cartessian product of the args.
return function (args) {
// Spot repeated args.
var countArgs = args.reduce(function (memo, el) {
return (memo[el] = (memo[el] || 0) + 1) && memo;
}, {}),
// Remove repeated args so that the cartessian product works properly and more efficiently.
uniqArgs = unique(args);
return uniqArgs
.reduce(function (memo, el) {
return flatten(memo.map(function (x) {
//...