Wiki Elegant

Histogram Function

Build a function that creates histograms. Every bar needs to be on a new line and its length corresponds to the numbers in the array passed as an argument. The second argument of the function represents the character to be used for the bar.

histogram(arr, char) ➞ str

Examples

histogram([1, 3, 4], "#") ➞ "#\n###\n####"

#
###
####

histogram([6, 2, 15, 3], "=") ➞ "======\n==\n===============\n==="

======
==
===============
===

histogram([1, 10], "+") ➞ "+\n++++++++++"

+
++++++++++

Notes

For better understanding try printing out the result.

Answer (1)
function histogram(arr, char) {
let result = ;
for (let i = 0; i < arr.length; i++) {
result += char.repeat(arr[i]) + \n;
}
return result.slice(0, 1);
}
Answer (2)
const histogram = (arr, char) => arr.map(x => char.repeat(x)).join(\n);
Answer (3)
function histogram(arr, char) {
let str = “”;
for (let num of arr) {
str += char.repeat(num) + \n;
}
return str;
}
Answer (4)
function histogram(arr, char) {
return arr.map(num => char.repeat(num)).join(\n);
}
Answer (5)
function histogram(arr, char) {
let result = ;
for (let num of arr){
result += char.repeat(num) + \n;
}
return result.slice(0, 1);
}

 

Answer (6)
function histogram(arr, char) {
let result = ;
for (let i = 0; i < arr.length; i++){
result += char.repeat(arr[i]) + \n;
}
return result.trim();
}
Answer (7)
function histogram(arr, char) {
let result = ;
for (let i = 0; i < arr.length; i++) {
let str = ;
for (let j = 0; j < arr[i]; j++) {
str += char;
}
result += str + \n;
}
return result;
}
Answer (8)
function histogram(arr, char) {
let result = ;
for (let num of arr) {
result += char.repeat(num) + \n;
}
return result.trim();
}
Answer (9)
function histogram(arr, char) {
let result = ;
for (let i = 0; i < arr.length; i++) {
let bar = ;
for (let j = 0; j < arr[i]; j++) {
bar += char;
}
result += bar + \n;
}
return result.trim();
}