Transposing a 2D-array in JavaScript
output = array[0].map((_, colIndex) => array.map(row => row[colIndex]));
map
calls a providedcallback
function once for each element in an array, in order, and constructs a new array from the results.callback
is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.
callback
is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. [source]
how to transpose 2d array using javascript
const testArray = [["SFT_DEA_LXD", 115494.1],
["SFT_ISA_LXD", 10082.31]];
const newArray = [];
const newArray1 = [];
testArray.forEach(item => {
newArray.push(item[0]);
newArray1.push(item[1]);
});
const result = [newArray, newArray1];
Transpose a two dimensional Array with one row and many columns into a two dimensional array with many rows and one column
I guess your goal as follows.
- From
var dataArr = shrinkLog.getRange(2,3,1,shrinkLog.getLastColumn()).getValues()
, you want to retrieve the result from[[data1, data2, data3,,,]]
to[[data1], [data2], [data3],,,]]
.
In your case, shrinkLog.getRange(2,3,1,shrinkLog.getLastColumn()).getValues()
returns [[data1, data2, data3,,,]]
. So when your goal is achieved with map
, the modified script is as follows.
Sample script:
var dataArr = shrinkLog.getRange(2,3,1,shrinkLog.getLastColumn()).getValues()[0].map(c => [c]);
Note:
- In this case, please enable V8 runtime.
Reference:
- map()
Transposing JavaScript Multi D arrays
You can so something like this, using map and for loop. But honestly I find this unnecessary. You could just do this from the get go in your loop. instead of pushing to row, you could try:
row[0][timeframes[t]] = "that long thing you have there"
const arr = [
[{
"ticker": "JPM"
},
{
"move": 0.01405944118170499
},
{
"move": 0.0337445573294628
},
{
"move": 0.1692882281117576
},
{
"move": 0.07636499188035195
},
{
"move": 0.8151371865267423
},
{
"move": 0.4537049320855997
}
],
[{
"ticker": "C"
},
{
"move": -0.01295986622073586
},
{
"move": 0.002689694224235595
},
{
"move": 0.05544868117343582
},
{
"move": -0.0457495911125243
},
{
"move": 0.7837535634777528
},
{
"move": 0.05665004788714745
}
],
[{
"ticker": "C"
},
{
"move": -0.01295986622073586
},
{
"move": 0.002689694224235595
},
{
"move": 0.05544868117343582
},
{
"move": -0.0457495911125243
},
{
"move": 0.7837535634777528
},
{
"move": 0.05665004788714745
}
],
]
const flatObj = (arr) => {
const flatObject = {};
const keys = ["ticker", "5", "10", "90", "120", "250", "500"]
for (let i = 0; i < arr.length; i++) {
for (const property in arr[i]) {
flatObject[keys[i]] = arr[i][property];
}
};
return flatObject;
}
const result = arr.map(ar => flatObj(ar))
console.log(result)
Transposing variable size array in javascript?
You could transpose the array by using arrays with the length of the outer array as length for every line.
var array = [[1, 2], [], [3], [4, 5, 6], [,,7]],
result = array.reduce((r, a, i, { length }) => {
a.forEach((v, j) => {
r[j] = r[j] || new Array(length).fill('');
r[j][i] = v;
});
return r;
}, []);
console.log(result);
Swap rows with columns (transposition) of a matrix in javascript
See article: Transpose An Array In JavaScript and jQuery
function transpose(a) {
// Calculate the width and height of the Array
var w = a.length || 0;
var h = a[0] instanceof Array ? a[0].length : 0;
// In case it is a zero matrix, no transpose routine needed.
if(h === 0 || w === 0) { return []; }
/**
* @var {Number} i Counter
* @var {Number} j Counter
* @var {Array} t Transposed data is stored in this array.
*/
var i, j, t = [];
// Loop through every item in the outer array (height)
for(i=0; i<h; i++) {
// Insert a new row (array)
t[i] = [];
// Loop through every item per item in outer array (width)
for(j=0; j<w; j++) {
// Save transposed data.
t[i][j] = a[j][i];
}
}
return t;
}
console.log(transpose([[1,2,3],[4,5,6],[7,8,9]]));
How to transpose 2D square matrix stored as 1D array in Javascript
You could take the length for the dimension of the array and map items on a specific index for a new array.
var array = [1 ,2, 3, 4, 5, 6, 7, 8, 9],
n = Math.sqrt(array.length),
transposed = array.map((_, i, a) => a[(i % n) * n + Math.floor(i / n)]);
console.log(transposed.join(' '));
Transpose irregular matrix in JavaScript
There are a lot of ways to solve this (as other answers demonstrate). Here's how I'd do it, as it minimizes the number of times we iterate over the data.
const data = [
[undefined, undefined],
[1, 2, 3, 4],
[1, 2],
[undefined, undefined, undefined],
[1, 2, 3, 4, 5, 6],
];
// get the length of the longest array
const maxLen = data.reduce((max, {length}) => Math.max(max, length), 0);
// make a new set of arrays
const result = Array.from({ length: maxLen }, (_, i) => data.map(col => col[i]));
console.log(result);
Related Topics
Remove Empty Elements from an Array in JavaScript
Rails 4: How to Use $(Document).Ready() With Turbo-Links
When Are You Supposed to Use Escape Instead of Encodeuri/Encodeuricomponent
Jquery Animate Backgroundcolor
What Are Valid Date Time Strings in JavaScript
How to Add a Key/Value Pair to a JavaScript Object
Origin Is Not Allowed by Access-Control-Allow-Origin
Load and Execute Order of Scripts
Insert HTML into View from Angularjs Controller
How to Deep Merge Instead of Shallow Merge
Calculate Age Given the Birth Date in the Format Yyyymmdd
How to Display a JavaScript Object
How to Make an Ajax Call Without Jquery