Our goal is to transpose an array of strings. For example:
terminal| h o w | | h a y | | a r e | → | o r o | | y o u | | w e u |
In JavaScript:
javascript// Initial array let array = ['how', 'are', 'you']; // Our goal let trans = ['hay', 'oro', 'weu'];
We can iterate through the array:
javascript// Initial array let array = ['how', 'are', 'you']; // Declare an empty array let trans = [...array].fill(''); // Iterating through the array to achieve our goal for(let i = 0; i < array.length; i ++){ for(let j = 0; j < array.length; j ++){ trans[i] = trans[i] + array[j][i]; } } console.log(trans); // ['hay', 'oro', 'weu']
We can achieve the same result using ES6:
javascript// Initial array let array = ['how', 'are', 'you']; // We can observe that: // trans = [array[0][0] + array[1][0] + array[2][0], // array[0][1] + array[1][1] + array[2][1], // array[0][2] + array[1][2] + array[2][2]]; // As trans is an array of sums, we can use 'map' and 'reduce' to get it. // trans = array.map( (string, i) => array[0][i] + array[1][i] + array[2][i]); // ----------------------|----------------- // | // | We can use 'reduce' // | to sum the elements // | // [...string].reduce( (acc, elem, j) => acc += array[j][i], ''); // In one line of code let trans = array.map((string, i) => [...string].reduce( (acc, elem, j) => acc += array[j][i], '')); console.log(trans); // ['hay', 'oro', 'weu']
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.