Hello Friends 👋,

Welcome To Infinitbility! ❤️

To get index value of element in react native have indexOf() and findIndex() method but both have different poupose of use.

Today, we will learn how to get index array elements in react native and we will see examples with an array of string and an array of objects.

Let’s first understand when use indexOf() or findIndex() method.

  • The indexOf() method is used for an array of primitive datatypes like string, number, etc or you can also say single dimension array.

  • The findIndex() method use when find index value from object element.

React Native indexOf() example

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    let users = ['infinitbility', 'notebility', 'repairbility'];
    setUsers(users);
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        index of notebility is {users.indexOf("notebility")}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Output

react native, array, indexOf, example
React Native, array indexOf example.

React Native findIndex() example

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating that no element passed the test.

import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet } from 'react-native';

export default function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    let users = [
      { id: 1, name: 'infinitbility' },
      { id: 2, name: 'notebility' },
      { id: 2, name: 'repairbility' },
    ];
    setUsers(users);
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>
        notebility index index  {users.findIndex(e => e.id == 2)}
      </Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Output

react native, findIndex, example
React Native, findIndex example.

Thanks for reading…