6

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.

5 Answers 5

11

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.

1
  • I like this best. It's the most concise. I would probably add some newlines though.
    – Evert
    May 5, 2018 at 1:40
5

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);

3

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(' '));

2

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\>'));

1
  • 1
    Although this will work, you generally want to use map on arrays and from on array-like objects. from is usually used to convert array-like objects into actual arrays with the same content, while map is used to make an array from another array with different content, based on the original content.
    – BoltKey
    May 5, 2018 at 1:23
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.