In the following short script (running in my browser):
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.map(function(age) {
return Math.sqrt(age) + "<br/>";
});
document.write(ages3);
I would like to print a column of square root values in the most concise manner possible (ideally using the map method above). I attempted to chain a join, e.g., return age.join(' ').Math.sqrt(age) + "<br/>"; but that was unsuccessful (no output was produced).
Thank you.
My solution using join
and map
.
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
document.write(ages.map(a => Math.sqrt(a)).join("<br>"));
I think this solution is pretty concise and does just what you want.
If you want to produce a (single) HTML string to output, you should use reduce
instead. .map
is for when you want to transform an array into another array.
const ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.reduce(function(accum, age) {
return accum + Math.sqrt(age) + "<br/>";
}, '');
document.write(ages3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With