
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding Transpose of a 2-D Array in JavaScript
We are required to write a JavaScript function that takes in a two-dimensional array and returns its transposed array.
The code for this will be −
Method 1: Using Array.prototype.forEach()
const arr = [ [0, 1], [2, 3], [4, 5] ]; const transpose = arr => { const res = []; arr.forEach((el, ind) => { el.forEach((elm, index) => { res[index] = res[index] || []; res[index][ind] = elm; }); }); return res; }; console.log(transpose(arr));
Method 2: Using Array.prototype.reduce()
const arr = [ [0, 1], [2, 3], [4, 5] ]; const transpose = arr => { let res = []; res = arr.reduce((acc, val, ind) => { val.forEach((el, index) => { acc[index] = acc[index] || []; acc[index][ind] = el; }); return acc; }, []) return res; }; console.log(transpose(arr));
The output in the console for both the methods will be −
[ [ 0, 2, 4 ], [ 1, 3, 5 ] ]
Advertisements