Problem:
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?
Solution:
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:
const fruits = [
{
name: "Apple",
id: 1
},{
name: "Pear",
id: 2
},{
name: "Banana",
id: 3
}
];
const names = fruits.map(fruit=>fruit.name) // => ["Apple", "Pear", "Banana"]
names.indexOf("Pear") // => 1