Home > Enterprise >  Change array elements
Change array elements

Time:07-10

There is an array

[ [ 'Alex', '167%' ],
  [ 'Benjamin', '127%' ],
  [ 'Elijah', '117%' ],
  [ 'Liam', '136%' ],
  [ 'Theodore', '135%' ],
  [ 'Mia', '128%' ] ]

I need to make it look like this

[ 'Alex                     167%',
  'Benjamin                 127%',
  'Elijah                   117%',
  'Liam                     136%',
  'Theodore                 135%',
  'Mia                      128%' ]

I need the elements of each nested array to be combined into a string and such a number of spaces are inserted between them so that the length of this string is 29 characters

CodePudding user response:

You could use a map combined with padEnd

const items = [
  ['Alex', '167%'],
  ['Benjamin', '127%'],
  ['Elijah', '117%'],
  ['Liam', '136%'],
  ['Theodore', '135%'],
  ['Mia', '128%']
];


const combined = items.map(([name, percent]) =>
  name.padEnd(29 - percent.length, ' ')   percent
);

console.log(combined);

  • Related