In javascript, I'm looking for a tidy way of processing an array such that the short, repeating sequences (tuples) in a collection become reduced into a more compact collection. I want to convert an array of length 3n to a collection of length n.
Here's an imaginary example:
// A flat (1-dimensional) array of numbers for input
var input = [
1, 11, 5,
2, 12, 10,
3, 13, 6,
4, 14, 11,
... ];
// A custom "lambda". This is my main intent, the rest is just plumbing.
var formatData = function(a,b,c) {
return { foo: a, bar: b, woot: c };
};
var output = input.reduceMulti(3, formatData); // ficticious 'reduceMulti'!
// output:
// [
// { foo: 1, bar: 11, woot: 5 },
// { foo: 2, bar: 12, woot: 10 },
// { foo: 3, bar: 13, woot: 6 },
// { foo: 4, bar: 14, woot: 11 },
// ...
// ]
Alternatively, those objects in output could easily be strings, or arrays, if formatData returned something different.
I'm looking for a solution a lot like reduce, except with the ability to reduce to more than a single value.
Bonus points for being performant, but ultimately the solution should be readable, maintainable, and usable.
inputvariable a list of lists or is the existing assignment right?inputarray is just a simple 1-dimensional array, formatted to make the groups of three clearer. (It is correct as is.)forloop is usually much faster.