I have an array of objects, e.g.
var arr = [
{"a": "x"},
{"b": "0"},
{"c": "k"},
{"a": "nm"},
{"b": "765"},
{"ab": "i"},
{"bc": "x"},
{"ab": "4"},
{"abc": "L"}
];
Let's say I am only interested in objects whose keys correspond to var input = ["ab", "bc"]
. It means that I want to extract all possible subarrays with result[i].length == 2
in the following way:
var result = [
[{"ab": "i"}, {"bc": "x"}],
[{"ab": "4"}, {"bc": "x"}] // or [{"bc": "x"}, {"ab": "4"}]
];
— that is, the order of objects in subarrays is absolutely not important: I am only interested in the fact that each subarray contains two objects — {"ab": ...}
and {"bc": ...}
.
If I was interested in var input = ["a","a","ab"]
, the result should be like this:
var result = [
[{"a": "x"}, {"a": "nm"}, {"ab": "i"}],
[{"a": "x"}, {"a": "nm"}, {"ab": "4"}]
];
I cannot find the way to achieve the desired result (assuming that input.length
may be much greater than 2 or 3 — even 15–20 may be not enough) without factorial-level amount of computations, which is not physically possible. Is there a way to have some reasonable performance for solving such a problem?
Important note: yes, obviously, for relatively large values of input.length
there theoretically may be possible to have very huge numbers of possible combinations, but in practice, result.length
will always be reasonably small (maybe 100–200, I even doubt that it could reach 1000...). But for safety, I would want to just set some limit (say, 1000), such that as soon as result.length
reaches this limit, the function just returns the current result
and stops.
arr
contains{"ab":value}
. If yes, get the next{"bc":value}
and put them both inresult
. Step 2. check ifarr
contains{"bc":value}
. If yes, get the next{"ab":value}
and put them both inresult
. And so on, which requires a factorial-level number of possible situations. – lyrically wicked yesterday["a", "a", "ab"]
? How should the "algorithm" decide if a value is part of the first a or the latter? Scan theinput
first and then decide that there's more than 1 a, the latter should receive the rest? Or were you perhaps actually looking for the product of found objects for each key? – Ilja Everilä yesterdayresult[i+1]
different fromresult[i]
? Yes. That's what matters. – lyrically wicked yesterday