Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map, and removing commas from an array in Javascript

Tags:

javascript

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.

like image 680
CaitlinG Avatar asked Dec 04 '22 20:12

CaitlinG


2 Answers

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.

like image 117
BoltKey Avatar answered Jan 01 '23 09:01

BoltKey


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);
like image 41
CertainPerformance Avatar answered Jan 01 '23 08:01

CertainPerformance