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);
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.
Share Improve this question edited May 5, 2018 at 0:43 cs95 402k104 gold badges735 silver badges790 bronze badges asked May 5, 2018 at 0:42 CaitlinGCaitlinG 2,0153 gold badges27 silver badges35 bronze badges5 Answers
Reset to default 14My 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);
You were on the right track. Just join()
the newly mapped array ages3
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.join(' '));
Alternatively you can use array.from
const ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
document.write(Array.from(ages, x => Math.sqrt(x)).join('<br\>'));
if you want new line between result then you can pass < br / > in side join function just line this:- return Math.sqrt(age).join('<br>'); if you want space between result then you can pass empty string in join function jus like this:- return Math.sqrt(age).join(' '); or if you want nothing then you can pas nothing inside jpin function just like this:- return Math.sqrt(age).join('');
var ages = [23, 22, 4, 101, 14, 78, 90, 2, 1, 89, 19];
const ages3 = ages.map(function(age) {
return Math.sqrt(age).join('<br\>');
// return Math.sqrt(age).join(' ');
// return Math.sqrt(age).join('');
});
document.write(ages3);