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]
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]]));
JavaScript / Google Script - Transpose Row Array into Column Array
In your script of var items = ss.getRange(16,4,1,endRange).getValues()
, items
is 2 dimensional array like [[value1, value2, value3,,,]]
. So, when your script is modified, it becomes as follows.
From:
var colArray = [];
for (var i=0; i<items.length; i++)
{
colArray.push([items[i]]);
}
}
To:
var colArray = [];
for (var i = 0; i < items[0].length; i++) {
colArray.push([items[0][i]]);
}
And,
From:
var colArray = items.map(function (el){
return [el];
});
To:
var colArray = items[0].map(function (el){
return [el];
});
Note:
Or, when you want to transpose the values including the several rows and columns, you can also use the following script.
const colArray = items[0].map((_, i) => items.map(row => row[i]));
References:
- map()
How to swap rows and columns of a 2d array?
You could iterate over the rows and columns and assign each element [i,j] to the transposed [j,i]:
/**
* Transposses a matrix.
* Assumption: mat is a non-empty matrix. i.e.:
* 1. mat != null
* 2. mat.length > 0
* 3. For every i, mat[i].length are equal and mat[i].length > 0
*/
public static int[][] transpose(int[][] mat) {
int[][] result = new int[mat[0].length][mat.length];
for (int i = 0; i < mat.length; ++i) {
for (int j = 0; j < mat[0].length; ++j) {
result[j][i] = mat[i][j];
}
}
return result;
}
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 arrayconst maxLen = data.reduce((max, {length}) => Math.max(max, length), 0);
// make a new set of arraysconst result = Array.from({ length: maxLen }, (_, i) => data.map(col => col[i]));
console.log(result);
How to Transpose an Array of Objects in Javascript?
There are several ways to approach this. Here is a function that creates a new data structure and returns it. It first finds out what is the largest size of a seat
array in the input, using Math.max
. Then it creates an array with that many rows, using Array.from
. Each generated row is populated with as many items as there are rows in the original data (4).
When there is no corresponding item to transpose, a default one is used instead (using ??
operator).
const transpose = arr =>
Array.from({length: Math.max(...arr.map(({seat}) => seat.length))}, (_, i) =>
({ seat: arr.map(({seat}) => seat[i] ?? {available: false, id: null}) })
);
// The sample data from the question:
const arr = [{seat: [{available: false, id: 1},{available: false, id: 5},{available: true, id: 9},{available: true, id: 13},{available: true, id: 17},{available: true, id: 21},{available: true, id: 25},{available: true, id: 29},{available: true, id: 33},{available: true, id: 37},{available: true, id: 41}]},{seat: [{available: true, id: 2},{available: true, id: 6},{available: true, id: 10},{available: true, id: 14},{available: true, id: 18},{available: true, id: 22},{available: true, id: 26},{available: true, id: 30},{available: true, id: 34},{available: true, id: 38},{available: true, id: 42}]},{seat: [{available: true, id: 3},{available: false, id: 7},{available: true, id: 11},{available: true, id: 15},{available: true, id: 19},{available: true, id: 23},{available: true, id: 27},{available: true, id: 31},{available: true, id: 35},{available: true, id: 39},{available: true, id: 43}, {available: true, id: 45},{available: true, id: 47}]},{seat: [{available: true, id: 4},{available: true, id: 8},{available: false, id: 12},{available: true, id: 16},{available: true, id: 20},{available: true, id: 24},{available: true, id: 28},{available: true, id: 32},{available: true, id: 36},{available: true, id: 40},{available: true, id: 44},{available: true, id: 46},{available: true, id: 48}]},]
const result = transpose(arr);
console.log(result);
Changing rows to columns javascript
What you're asking looks a little weird because you have different lengths and you're ignoring undefined values, but it is still achievable.
Don't use for..in
loops for Array, use a normal for
. Also, you'll need to know how many items you'll have in your new parent Array, which is the max of the lengths of the original child Arrays.
var arrR = [ // will refer to "down" and "across" as in this literal
[1],
[1, 2],
[1, 2, 3],
[4, 2, 3],
[4, 5, 3],
[4, 5, 6]
];
function r2c(arr) {
var arrC = [], // next get the longest sub-array length
x = Math.max.apply(Math, arr.map(function (e) {return e.length;})),
y = arr.length,
i, j;
for (i = 0; i < x; ++i) { // this is the loop "down"
arrC[i] = [];
for (j = 0; j < y; ++j) // and this is the loop "across"
if (i in arr[j])
arrC[i].push(arr[j][i]);
}
return arrC;
}
var arrC = r2c(arrR);
/* [
[1, 1, 1, 4, 4, 4],
[2, 2, 2, 5, 5],
[3, 3, 3, 6]
] */
You should still consider if you're happy with [[1], [1, 2], [1]]
becoming [[1, 1, 1], [2]]
, which I would consider unexpected (the position of 2
is completely lost), but seems to be what you intend.
Related Topics
React-Router Scroll to Top on Every Transition
Check If String Contains Only Digits
How to Run Two Jquery Animations Simultaneously
Is There a JSON Equivalent of Xquery/Xpath
JavaScript Convert Hsb/Hsv Color to Rgb Accurately
How to Poll a Google Doc from an Add-On
What Do Curly Braces Inside of Function Parameter Lists Do in Es6
How to Check in JavaScript If One Element Is Contained Within Another
JavaScript Hard Refresh of Current Page
Generate PDF from HTML Using PDFmake in Angularjs
How to Synchronously Determine a JavaScript Promise's State
How to Offset the Center Point in Google Maps API V3
How to Select Option in Drop Down Protractorjs E2E Tests
Canvas.Todataurl() Securityerror
How to Get the Fragment Identifier (Value After Hash #) from a Url