Operate elements of an array

0

It is possible to operate elements of an array in JavaScript without the need to use a repeat structure as for or while. For example, suppose I have an array with 10 elements and I want to get each element and divide them by 2 without using the for or while statements?

    
asked by anonymous 25.01.2018 / 06:10

1 answer

4

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

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

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

See working at Repl.it

    
25.01.2018 / 10:05