I saw an answer online with something like this:
myArray.map(e=>e.id).indexOf("something")
but it didnt really make sense to me, as it seems like this "." operatore is going to be applied after the map function is executed? I guess it gets applied to every iteration of the map function, however whats confusing me is, isnt "indexOf" a method of the array object? Does the map function return an array? Also how is it being applied to every index, does the map function return after every iteration and run again?
2
Answers
Yes, the map function returns an array. It can extract data from each element of a given array then stores it in a new array and finally returns that array. The indexOf function is used to get the index of some value in an array. So in this case it returns the index of "something" from the array that gets returned from the map function. It is only executed once, after the map function returned the new array.
Example:
When you map an array in JS, it gives a function as input (let’s say
mapperFunc
).mapperFunc
is executed on every element in that array. Each array element is passed tomapperFunc
as its input and the function output will return as the result. All those results together will make up a new array which would be the result of the mapping:you can concise the above code using lambda:
suppose that you have an array of numbers and you want to multiply all its elements by 2:
you can apply any function that is applicable to an array on the
map
result. For example,indexOf
: