I've recently started JS from YouTube. I need help with some logic. I've an array of radius:
const radius = [3,1,2,4]
I want to calculate the diameter and also print the largest diameter. I tried:
const radius = [3, 1, 2, 4];
const myLogic = function (currentRadius) {
return (2 * currentRadius)
}
const calculate = function (radius) {
const output = [];
radius.map(currentValue => output.push(myLogic(currentValue))).reduce((max, currentItem) => {
if (max < currentItem) {
max = currentItem;
}
console.log("Largest diameter: ",max);
}, 0)
return output;
}
console.log(calculate(radius));
Output:
1
undefined
undefined
undefined
[ 6, 2, 4, 8 ]
How can I get the largest Diameter. Please help.
CodePudding user response:
There are couple of minor issues. 1) you are not returning value in map
function, thus the array is not having the values to be used for reduce
call 2) in reduce method missing return on max
const radius = [3, 1, 2, 4];
const myLogic = function (currentRadius) {
return 2 * currentRadius;
};
const calculate = function (radius) {
return radius.map(myLogic).reduce((max, currentItem) => {
if (max < currentItem) {
max = currentItem;
}
console.log("Largest diameter: ", max);
return max;
}, 0);
};
console.log(calculate(radius));
CodePudding user response:
You could try the Math.max() method to get the largest number.
const radius = [3, 1, 2, 4];
const myLogic = function (currentRadius) {
return (2 * currentRadius)
}
const calculate = function (radius) {
radius = radius.map(currentValue => myLogic(currentValue));
let max = Math.max(...radius);
console.log(max);
}
CodePudding user response:
Using a for...of
loop is useful here:
function double (num) {
return num * 2;
}
function calculate (radii) {
const diameters = [];
let max = 0;
for (const radius of radii) {
const diameter = double(radius);
diameters.push(diameter);
if (diameter > max) max = diameter;
}
console.log(`Largest diameter: ${max}`);
return diameters;
}
const radii = [3, 1, 2, 4];
console.log(calculate(radii));