Guest User

Untitled

a guest
Jan 22nd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. /**
  2. * Transpose an array of arrays using matrix transposition.
  3. * The array is returned, *NOT* transposed in place.
  4. *
  5. * Handles matrixes where the number of rows != number of columns.
  6. * The number of columns in each row must be the same.
  7. * E.g.
  8. [ | [
  9. [1,2,3], | [1,2],
  10. [4,5,6], | [3,4],
  11. [7,8,9], | [5,6],
  12. ] | ]
  13. becomes | becomes
  14. [ | [
  15. [1,4,7], | [1,3,5],
  16. [2,5,8], | [2,4,6],
  17. [3,6,9], | ]
  18. ] |
  19. * @param {Array} array The array to transpose.
  20. * @return {Array}
  21. */
  22. function transpose( array ) {
  23. let newArray = [];
  24.  
  25. for (let i = 0, len = array[0].length; i < len; i++) {
  26. newArray.push( [] );
  27. for (let j = 0, len = array.length; j < len; j++) {
  28. newArray[i].push( array[j][i] );
  29. }
  30. }
  31.  
  32. return newArray;
  33. }
Add Comment
Please, Sign In to add comment