Align Strings using PadEnd
Alwar G
Posted on June 10, 2020
Now we are going to talk about Align Strings using PadEnd as shown in the above image. If you are not familiar with padEnd then read this first.
Ok let's start.
HTML:
<div id="table"></div>
JS:
let stringsMap = {
Name: 'Alwar G',
Age: '24',
'Marital Status': 'single',
Skills: 'HTML, CSS, JS'
};
let objKeys = Object.keys(stringsMap);
let keysSpace = Math.max(...objKeys.map(el => el.length));
let table = document.getElementById('table')
objKeys.forEach((key) => {
let ele = document.createElement('pre');
ele.innerHTML = `${key.padEnd(keysSpace)}: ${stringsMap[key]}`;
table.appendChild(ele);
});
Here we have strings map
to disaplay the details. From the strings map
we need to find which key string is the longest string in the keys. For that first we need to get all key strings length. that is
let objKeys = Object.keys(stringsMap);
objKeys.map(el => el.length);
// [4, 3, 14, 6]
After this we should find the longest number from the above array
Math.max(...objKeys.map(el => el.length));
// 14
Now we got the maximum string length. So, we need to align the strings based on this length. Here PadEnd
will play a virtual rule. How?🤔
let's see
let table = document.getElementById('table')
objKeys.forEach((key) => {
let ele = document.createElement('pre');
ele.innerHTML = `${key.padEnd(keysSpace)}: ${stringsMap[key]}`;
table.appendChild(ele);
});
While iterating object, we are creating the pre element and append this element to the table
div.
Also we are setting the innerHTML of pre element as ${key.padEnd(keysSpace)}: ${stringsMap[key]}
. Here key.padEnd(keysSpace)
will make the needed space to make the correct alignment.
Now we got the output.
Thanks for reading. I hope you enjoyed this post.
Posted on June 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024