I have developed a function that extracts all elements from a 2D array by rows and converts them into a 1D array. The input array can have varying numbers of columns and rows.
For example:
let arr = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
];
This will return:
[1, 5, 9, 2, 6, 10, 3, 7, 11, 4, 8, 12]
The function I have created is as follows:
convertList = (list) => {
let result = [];
let listTotalEntries = R.sum(R.map(R.length)(list));
let mod = R.modulo(R.__, list.length);
let counterRow = -1;
for (let i = 0; i < listTotalEntries; i++) {
if (mod(i) === 0) {
counterRow++;
}
if (list[mod(i)][counterRow]) {
result.push(list[mod(i)][counterRow]);
console.log(list[mod(i)][counterRow]);
}
}
console.log(result);
return result;
};
Inquiry: Currently, this function only works with square matrices. How can I modify it to handle arrays with varying lengths?
For instance:
let arr = [
[1, 2],
[],
[9, 10, 11, 12]
];
Desired output:
[1, 9, 2, 10, 11, 12]
Thank you for your assistance!
Muff