HashMap HashMap - 18 days ago 6
Javascript Question

format array to output in node.js

var toFormat = [[1, "one", "unu"], [2, "two", "du"], [3, "three", "tri"], [4, "four", "kvar"]];


I need to output array
toFormat
so it should look like this:

1 (one)
2 (two)
3 (three)
4 (four)


(The third element of every sub-array is not used)
How to do that?

EDIT: The loop is here

var res = [];
for(var i=0;i<toFormat.length;i++){
res.push(toFormat[i][1]+" ("+toFormat[i][2]+")");
}
console.log(res.join("\n"))

Answer

There are a ton of ways this can be done. I'd personally recommend using a for...of loop, like this

// defining the array to loop over
const toFormat = [
  [1, 'one', 'unu'],
  [2, 'two', 'du'],
  [3, 'three', 'tri'],
  [4, 'four', 'kvar']
];

for (let i of toFormat) {
  console.log(i[0] + " (" + i[1] + ")");
}

Of course, if you want this as a string instead of being printed you can do this instead

// defining the array to loop over
const toFormat = [
  [1, 'one', 'unu'],
  [2, 'two', 'du'],
  [3, 'three', 'tri'],
  [4, 'four', 'kvar']
];

let formatted = "";
for (let i of toFormat) {
  formatted += (i[0] + " (" + i[1] + ")\n");
}
console.log(formatted);