Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Rebecca Jensen
11,580 PointsCan I perform Math.max() on a named array?
I've written some code that looks at an array of strings that are numbers, and adds up each string of numbers (e.g. '123' becomes 6). Now I want to compare the integers in the array (I did convert them to integers), to find the largest number. I am trying to use Math.max() to do that, but it doesn't seem to work when I call the name of my array to it.
Can I use Math.max() to do this? Do I need to do more to the array first to prepare it for Math.max()? Should I use another method?
Thanks
Code here: https://repl.it/I0e5/21
And below:
var ccNumbers = ['1111','--34-1234', '21-11', '3111', '9111'];
function addDigits(number){
var sum = 0; //store the sum
var sumArray = [];//store several sums to print
for ( x = 0; x < ccNumbers.length; x++ ) { //loop through ccNumbers array
var ccNmbr = ccNumbers[x]; //pick out one array item and store it in ccNmbr
for ( z = 0; z < ccNmbr.length; z++) {
ccNmbr = ccNmbr.replace("-", 0);
ccNmbr = ccNmbr.replace(" ", 0);
} //removes dashes, replaces with 0's, to avoid NaN
for ( y = 0; y < ccNmbr.length; y++ ) { //loop through each digit in ccNmbr
sum += parseInt(ccNmbr.charAt(y), 10); //add each digit to the sum
} //close adding digits loop
sumArray.push(sum); //add sum to an array
sum = 0; //reset sum to 0 for the next loop
} //close looping through array loop
largest = Math.max(sumArray);
return largest;
}
addDigits();
1 Answer
james south
Front End Web Development Techdegree Graduate 33,271 Pointsyes. use the spread operator ... let max = Math.max(...myArray);
Rebecca Jensen
11,580 PointsRebecca Jensen
11,580 PointsA spread operator! Was just what I needed. I'm surprised I didn't encounter it in all of my Googling. Now that I have a term to search, I've found an article on other cool ways to use this: https://davidwalsh.name/spread-operator
Thanks!