Reputation: 652
In Javascript, how to convert a single dimensional array into a multidimensional array of unspecified depth or length.
Example:
let input = ['a','b','b','b','a','a','b','b','b','c','c','a','a','b','b'];
const makeMatrix = () => {}
let output = makeMatrix(input);
// output: ['a',['b','b','b'],'a','a',['b','b','b',['c','c']],'a','a',['b','b']]
What should the makeMatrix function look like to accomplish this task? Assume that values always move in a linear forward direction, but might possibly cut backward. So a always leads to b. An a would never hop to c. But c might drop back down to a.
This is to try to convert heading elements into a table of contents. Making a simple single tier toc is easy, but making a multi tiered one is wracking my brain. I have looked through a number of solutions, but have not seen anything that solves this particular problem.
Upvotes: 4
Views: 269
Reputation: 14927
Alternative version, using JSON building/parsing:
const input = ['a', 'b', 'b', 'b', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'a', 'a', 'b', 'b'];
const result = JSON.parse(Object.entries(input).reduce((json, [key, val]) => {
const jsonVal = JSON.stringify(val);
const diff = key > 0 ? val.charCodeAt(0) - input[key - 1].charCodeAt(0) : 0;
if (diff > 0) {
json += ',['.repeat(diff) + jsonVal;
} else if (diff < 0) {
json += ']'.repeat(-diff) + ',' + jsonVal;
} else {
json += (key > 0 ? ',' : '') + jsonVal;
}
return json;
}, '[') + ']'.repeat(input.slice(-1)[0].charCodeAt(0) - input[0].charCodeAt(0) + 1));
console.log(result);
This basically builds a JSON string using Array.reduce
on the input array, adding each item and comparing key codes to include the right amount of opening/closing brackets in the process.
Upvotes: 2
Reputation: 386520
You could take a level variable and a levels array for pushing unknown elements.
var input = ['a', 'b', 'b', 'b', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'a', 'a', 'b', 'b'],
levels = [[]],
level = 0,
result;
input.forEach(v => {
var l = level;
do {
if (levels[l][0] === v) {
level = l;
levels[level].push(v);
return;
}
} while (l--)
levels[level].push(levels[level + 1] = [v]);
level++;
});
result = levels[0][0];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 4
Reputation: 783
The dumb eval solution I had in mind, if it's what you wanted it can be made neat...
function toMulti(arr) {
let str = "[";
let level = 1;
const charLevels = { a: 1, b: 2, c: 3 };
arr.forEach(char => {
const charLevel = charLevels[char];
if (level < charLevel) {
for (let i = 0; i < charLevel - level; i++) {
str += "[";
}
}
if (level > charLevel) {
for (let i = 0; i < level - charLevel; i++) {
str += "],";
}
}
level = charLevel;
str += `'${char}',`;
});
for (let i = 0; i < level; i++) {
str += "]";
}
return eval(str);
}
Upvotes: 3