0

What does mean the index "[0]" in the end of the filter function or in any kind of function that It is added? For example let's say that I am importing a JSON data from a file, so I added this code

<Home dish={this.state.dishes.filter((dish) => dish.featured)[0]} />

As you can see It has added the [0] in the end, what does it mean? It is used for what? If it is something that could be added in many functions, and not just in the filter function, for what is used then?

  • 2
    The first result of the array returned by filter. filter always returns an array of all matches. Honestly, I don't understand why people use filter instead of just find even when they don't need to support IE – user120242 Jul 16 '20 at 17:42
  • 1
    Does this answer your question? [What does this symbol mean in JavaScript?](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript) – Heretic Monkey Jul 16 '20 at 17:46

2 Answers2

2

It takes the first item of the result array.

A better approach is to use Array#find instead of Array#filter.

<Home dish={this.state.dishes.find((dish) => dish.featured)} />
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

That means to get the first item in the array and return it.
That statement is basically just saying "filter all dishes in the state and return all that are 'featured' and return the first item in the array"