2
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 Answer 1

3

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'

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.