Search code examples
javascriptarraysconcatenation

How can i combine values in two arrays?


i have this 4 Arrays:

const units = [[ "deg" ], [ "px" , "px" ]];
const values = [[ 0 ], [ 0 , 0 , 0 ]];

I wanto to combine to this:

const result = ["0deg", "0px, 0px, 0"];

How can i do that?


Solution

  • You can use two .map() methods, one for iterating over the values in your values array, and another for iterating over the values in each inner array. The outer map is used to map the array values inside of values to strings. These string are formed by mapping the inner arrays to individual "<number><unit>" strings. The <number> (ie: n) is retrieved by the inner callback method from .map(). The <unit> is calculated by retrieving the associated array value from the units array using the indexes i and j. If the associated value returns a falsy value (eg: undefined), then it will default to an empty string. This array of ["<number><unit>", ...] strings can then be joined together to form one string, separated by a comma using .join(', ')

    const units = [[ "deg" ], [ "px" , "px" ]];
    const values = [[ 0 ], [ 0 , 0 , 0 ]];
    
    const result = values.map(
      (arr, i) => arr.map((n, j) => `${n}${units[i][j] || ""}`).join(', ')
    );
    console.log(result);