Operating array elements

Asked

Viewed 51 times

0

It is possible to operate elements of an array in Javascript without the need to use a repetition structure as for or while. For example, suppose I have an array with 10 elements and wish to take each element and divide it by 2, without using the for or while commands is possible?

1 answer

4


If I understand correctly, you want to numerically divide each element of the array by 2, so yes, it is possible to do this without the loop repeating (and it is even recommended to do).

The solution is to use the Array.prototype.map, executing an expression for each of the elements. Aligned with Arrow functions, the code becomes quite simple:

const half = [2, 4, 6, 8].map(it => it/2);  // [1, 2, 3, 4]

See working on Repl.it

  • Thanks for the answer, is it a Lambda Expression? Much like java.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.