Calculate the length of each string within an array with the .map method

1

Good morning, I'm not sure how the map method works, does one function for each element of array as foreach ? Thanks

I would like to know how to do this = >

Take an array of strings and turn it into an array of numbers indicating the length of each string using Array.map .

- '['Los Angeles', 'New York', 'Huston'] => [11, 8, 6]'
    
asked by fran 08.12.2017 в 15:42
source

2 answers

3

In a simple line:

var a = ['Los Angeles', 'New York', 'Huston'].map(x => x.length);

console.log(a);
  

The map () method creates a new array with the results of the call to the indicated function applied to each of its elements.

+ info

    
answered by 08.12.2017 в 15:47
0

If friend is very similar to forEach for each of the iterations we make changes in the element and generate a new array with the changes I hope you help greetings

var a = ['Los Angeles', 'New York', 'Huston'].map(x => x.length);

$("#btn").click(function(){
  $(".p").text(a)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="btn" type="button" name="button">cambiar array con map</button>
<p class="p">'Los Angeles', 'New York', 'Huston'</p>
    
answered by 08.12.2017 в 16:26