code code - 11 months ago 49
Javascript Question

How to format the element inside an array?

I have three arrays for example:

var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";

for (var i = 0; i < name.length; i++) {
temp = name[i] + " " + type[i];

for (var i = 0; i < name.length; i++) {
// I call here function to display all element of array `all`

The output is:

wheel car
rectangle shape
moon sky

But the format of output is not nice. I want to shift the element of array
before add them to array
, so I want the output to be like:

wheel car
rectangle shape
moon sky

My question is: how can I shift elements of the array to add them to another array and store them in a way that allows to me to display the elements like form above ?

Answer Source

You should calculate which is the longest string in the first array so to know in advance how many spaces you need to append to correctly pad the string

var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];

/* sorting the values of the first array by length desc,
 * then get the length of the first element 
var padding = n.sort(function(a, b) {
  return a.length <= b.length;
})[0].length + 1; 

n.forEach(function(el, i) {
  all.push(el + " ".repeat(padding - el.length) + t[i]);


"rectangle car"
"wheel     shape"
"moon      sky"

codepen demo