To find a single item in a list or array in JavaScript, you can use the Array.prototype.find()
method.
Here's an example code snippet:
index.tsx114 chars6 lines
In this example, we have an array called list
with the values [1, 2, 3, 4, 5]
. We then use the find()
method to search the array for the element with the value 3
.
The find()
method takes a function as an argument, which is used to test each element in the array. In this case, we use an arrow function with the parameter element
to check if the current element is equal to 3
.
The find()
method returns the first element that satisfies the condition in the function, which in this case is the element with the value 3
. We assign this value to the variable item
, and then log it to the console.
gistlibby LogSnag