If you're facing a complex problem, my suggestion would be to break it down into two simpler parts:
- First, gather all values from the inner arrays (
z
) into a single list using flatMap
- Next, determine the minimum and maximum values within this resulting list
flatMap
offers various implementations, with potential plans to introduce flattening as a standard array feature in browsers.
If the "no loops" constraint is a strict requirement, we can explore alternative solutions later on. For now, here's an initial approach to implementing flatMap
for 3D arrays using reduce
, concat
, and map
.
const flatMap = (f, xs) => xs.reduce(
(acc, ys) => acc.concat(ys.map(zs => f(zs))),
[]
);
By calling this function with a method that retrieves a particular element n
from each zs
array, you can obtain a list of those elements.
flatMap(zs => zs[1], [ /* .... */ ]); // returns all elements at index `n` in the third dimension
Subsequently, applying Math.min
and Math.max
operations becomes convenient through spreading or reducing:
const minAge = Math.min(...flatMap(zs => zs[1], [ /* ... */ ]));
In a simulated scenario:
const data = [
[
["Joe", 27, "US"],
["Mark", 34, "UK"]
],
[
["Alex", 22, "PK"]
]
];
const flatMap = (f, xs) => xs.reduce(
(acc, ys) => acc.concat(ys.map(f)),
[]
);
// Utilities
const max = xs => Math.max(...xs);
const min = xs => Math.min(...xs);
const pluck = k => o => o[k];
const minN = n => d => min(flatMap(pluck(n), d));
const maxN = n => d => max(flatMap(pluck(n), d));
const minAge = minN(1);
const maxAge = maxN(1);
console.log(
"Minimum age:", minAge(data),
"Maximum age:", maxAge(data)
)
If you are truly adamant about avoiding loops, recursion might be the only viable alternative. While reimagining flatMap
recursively may not result in elegant code, let me know if you wish to delve into that territory.