Convert 2-dimensional array to string in Javascript

Viewed 68
const adFormats = {
  leaderboard: {
    sizes: [
      [728, 90],
    ],
  },
  rectangle: {
    sizes: [[320, 250], [300, 250], 'fluid'],
  },
  halfpage: {
    sizes: [[300, 600], [320, 250], [300, 250]],
  },
};

this is where it goes wrong

Object.keys(adFormats).forEach(key => {
  adFormats[key].sizes.forEach(size => {
    if (typeof size !== 'string') {
      companionSizes += `${size[0]}x${size[1]}`; 
    }
    companionSizes += '|';
  });
  companionSizes += ',';
});
// expected output: '728x90,320x250|300x250,300x600|320x250|300x250'

I would like to make this cleaner with join() and/or map(). In order to prevent the use of leading or trailing separators. Also to have some cleaner code.

1 Answers

You could filter the inner arrays and join all nested and map the outer arrays.

const
    adFormats = { leaderboard: { sizes: [ [728, 90]] }, rectangle: { sizes: [[320, 250], [300, 250], 'fluid'] }, halfpage: { sizes: [[300, 600], [320, 250], [300, 250]] } },
    result = ['leaderboard', 'rectangle', 'halfpage']
        .map(k => adFormats[k].sizes
            .filter(Array.isArray)
            .map(a => a.join('x'))
            .join('|')
        )
        .join(',')

console.log(result); // '728x90,320x250|300x250,300x600|320x250|300x250'

Related