Skip to content

Instantly share code, notes, and snippets.

@damirm
Created August 26, 2016 15:29
Show Gist options
  • Save damirm/b191099d95f04dd19c48d083387cfaeb to your computer and use it in GitHub Desktop.
Save damirm/b191099d95f04dd19c48d083387cfaeb to your computer and use it in GitHub Desktop.
'use strict';
const source = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const expected = [0, 4, 8, 1, 5, 9, 2, 6, 3, 7];
function transpose(arr, columns) {
const rows = Math.ceil(arr.length / columns);
return arr.reduce((result, v, i) => {
const col = Math.ceil((i + 1) / rows);
const row = i % rows;
result[row * columns + col - 1] = v;
return result;
}, []).filter(v => typeof v != 'undefined');
}
function equals(a, b) {
return JSON.stringify(a) == JSON.stringify(b);
}
const result = transpose(source, 3);
console.log(result, equals(result, expected));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment