skip to Main Content

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


  1. 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
    Login or Signup to reply.
  2. 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 to mapperFunc 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:

    myArray.map(function mapperFunc(arrayElement) {
        return mappedElement;// do some calcuations
    });
    

    you can concise the above code using lambda:

    myArray.map((arrayElement) => mappedElement);
    

    suppose that you have an array of numbers and you want to multiply all its elements by 2:

    [1, 2, 3, 4, 5].map(elem => elem * 2);// output will be [2, 4, 6, 8, 10]
    

    you can apply any function that is applicable to an array on the map result. For example, indexOf:

    [1, 2, 3, 4, 5].map(elem => elem * 2).indexOf(6); // will return 2
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search