ReactJS check element exists in Array


You can use array indexOf method to check whether an element exists in Array or not. Here in this tutorial, we are going to explain how you can use this method to check if array contains value. You can use our online editor to edit and run the code online.


ReactJS check element exists in Array JavaScript Example

Array indexOf method returns -1 if element is not found in array else it returns index of element. Here is an example of Array indexOf method.

Example:

<script type="text/es2015">
function MyFunction() {
 var myArray = [5, 10, 11, 2, 4];
 if(myArray.indexOf(99) > -1){
 var result =  <li>Item Exists in Array at index = {myArray.indexOf(99)} </li>
}else{
 var result = <li>Item Not Found in Array.</li>
}
  return (
    <ul>{result}</ul>
  );
}

ReactDOM.render(
  <MyFunction />,
  document.getElementById('root')
);
</script>

Try it »

Output of above example-

ReactJS check element exists in Array

Advertisements

User Ans/Comments

The title indicates that this problem solving approach is react-specific. But, way off the mark! This is good old plain js and not framework or library related.
 shaedrich

Add Comment

📖 Read More