Making a number list from array elements

Hi there!

I’d like some advice on how to more concisely write the following code:

newArr[i] = Math.max(arr[i][0], arr[i][1], arr[i][2], arr[i][3]);

So I can get it to look more professional and concise. The Math.max function requires a list of numbers, which the above code does indeed provide. However it’s unsightly. There must be a better way than explicitly referring to every single array element like that.

I was wondering if I could use a map for this but I don’t know how?

Thanks :slight_smile:

Try the spread operator to break up the nested array arr[i] into a comma separated list of values.

Math.max(…arr[i])

and then assign it to newArr[i].

Are you trying to find the max value among the first 4 elements of the array or is it across the entire array?

1 Like

Bingo. Worked a treat thanks very much looks much nicer now. I’ll post the code below so anyone else who might read this can see it:

newArr[i] = Math.max(...arr[i]);

Produces the same successful result as the code above, only it looks much nicer thank you :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.