Skip to Content
Array methods in React

Array methods in React

Hey and welcome! Thanks so much for stopping by. If you are looking to learn how to work with array methods beyond map in React such as filter(), sort(), or some() you’re in the right place! I’ll show you how to use array methods in React.

In this article we are going to take a React List that’s mapped out, filter through it with the Array.filter() method, then we’ll sort our React List with Array.sort() and finally we’ll test the contents of the list using the Array.some() method.

Estimated reading time: 7 minutes

In this project we're using React + Typescript, but if you have no experience with Typescript that's okay. Just change the file extensions from .ts to .js and .tsx to .jsx ? I've left comments for the code below to know what you can ignore if you're using a regular create-react-app application.

To get the most out of this article, check out the build here and check out the source code here.

To get started

Open your terminal in VSCode and run:

npx create-react-app my-app

Or if you’re using Typescript:

npx create-react-app my-app --template typescript

Want more practice with Typescript? Check out how to build with WordPress and Typescript in this project article.

File Structure

In the /src directory create a new folder called /components

Inside the components folder create three files:

  • BestNovel.tsx
  • Button.tsx
  • List.ts

The List Data

The list data is housed inside our components folder. Because there is no JSX in this file, this file ends with .ts. This file houses our List which is an array of objects. Each object stores data about Nebula Award Winning Novels written by a woman.

// If you aren't using Typescript
// Ignore the interface and ': IList[]' from the List export below

export interface IList {
    Title: string,
    Author: string,
    Year: number,
    id: number
}
// Female Nebula Award Winners for Best novel:
export const List: IList[] = [
    {Title: 'The Left Hand of Darkness', Author: 'Ursula K. Le Guin', Year: 1969, id: 1},
    {Title: 'The Dispossessed', Author: 'Ursula K. Le Guin', Year: 1974, id: 2},
    {Title: 'Dreamsnake', Author: 'Vonda McIntyre', Year: 1978, id: 3},
    {Title: 'The Falling Woman', Author: 'Pat Murphy', Year: 1987, id: 4},
    {Title: 'Falling Free', Author: 'Lois McMaster Bujold', Year: 1988, id: 5},
    {Title: 'The Healer\'s War', Author: 'Elizabeth Ann Scarborough', Year: 1989, id: 6},
    {Title: 'Tehanu: The Last Book of Earthsea', Author: 'Ursula K. Le Guin', Year: 1990, id: 7},
    {Title: 'Doomsday Book', Author: 'Connie Willis', Year: 1992, id: 8},
    {Title: 'Slow River', Author: 'Nicola Griffith', Year: 1996, id: 9},
    {Title: 'The Moon and the Sun', Author: 'Vonda McIntyre', Year: 1997, id: 10},
    {Title: 'Parable of the Talents', Author: 'Octavia E. Butler', Year: 1999, id: 11},
    {Title: 'The Quantum Rose', Author: 'Catherine Asaro', Year: 2001, id: 12},
    {Title: 'The Speed of Dark', Author: 'Elizabeth Moon', Year: 2003, id: 13},
    {Title: 'Paladin of Souls', Author: 'Lois McMaster Bujold', Year: 2004, id: 14},
    {Title: 'Powers', Author: 'Ursula K. Le Guin', Year: 2008, id: 15},
    {Title: 'Blackout/All Clear', Author: 'Connie Willis', Year: 2010, id: 16},
    {Title: 'Among Others', Author: 'Jo Walton', Year: 2011, id: 17},
    {Title: 'Ancillary Justice', Author: 'Ann Leckie', Year: 2013, id: 18},
    {Title: 'Uprooted', Author: 'Naomi Novik', Year: 2015, id: 19}
]

We’re importing this List into our BestNovel.tsx file at the top.

Want more practice working with lists? Check out how to create an Accessible To Do list in React here.

Import Statements

At the top of our BestNovel.tsx file we’re importing the following:

import React, { useState } from 'react'
import Button from './Button'
import { List } from './List'

At the top of our Button.tsx component we’re just importing React:

import React from 'react'

Finally, at the top of our App.tsx component, we’re importing the following:

import React from 'react';

import BestNovel from './components/BestNovel';

import './App.css'

State

Back in our BestNovel.tsx component, we’re using two pieces of state the newList and the newTitle. We’ll update our App component based on these pieces of state.

const BestNovel = () => {    
    const [newList, setNewList] = useState([<li></li>])
    const [newTitle, setNewTitle] = useState('')

// onClick handlers here

// return jsx here
}

In the BestNovel.tsx return statement below, we can see where each piece of state is being declared.

return (
        <>
        <h1>Novels by Women who've won a Nebula Award:</h1>
        <ul>
            {List.map(list => (
                <li key={list.id}>
                    <span className='author'>{list.Author} - </span>
                    <span className='title'>{list.Title} - </span>
                    <span className='year'>{list.Year} </span>
                    </li>
            ))}
        </ul>
        <>
        <div className='filtered-list'>
            <h2>{`${newTitle}`}</h2>
            <ul>{newList}</ul>
            </div>
        <div className='buttons-bar'>
            <Button onClick={handleFilter} name="Filter Novels that won in the 2000's" />
            <Button onClick={handleSort} name='Sort the authors by first name' />
            <Button onClick={handleSome} name="Some Author's names Ursula exist" />
        </div>
        </>
        </>
    )

In our onClick handlers we are going to change the state of our newList component from an empty list item to whichever list we’ll be returning. We are also updating the newTitle piece of state within each handler as well.

The App Component

The App component is simply putting out the BestNovel.tsx component. This full code is below:

import React from 'react';
import BestNovel from './components/BestNovel';
import './App.css'

function App() {
  return (
    <div className="App">
      <BestNovel />
    </div>
  );
}

export default App;

The meat of our work is within the BestNovel.tsx component.

The Buttons

We have a Button.tsx component in our components folder. That code is below and it’s very basic. It has a name prop for the button label, and an onClick prop for the onClick function.

import React from 'react'

// If you aren't using Typescript
// Ignore the interface and ': React.FC<IButton>' from 
// the Button export below

interface IButton {
    name: string,
    onClick?: () => void
}

const Button: React.FC<IButton> = ({name, onClick}) => {
    return <button onClick={onClick}>{name}</button>
}
export default Button

We’re implementing the button in our BestNovel component like this:

        <div className='buttons-bar'>
            <Button onClick={handleFilter} name="Filter Novels that won in the 2000's" />
            <Button onClick={handleSort} name='Sort the authors by first name' />
            <Button onClick={handleSome} name="Some Author's names Ursula exist" />
        </div>

As you can see we have defined the name prop on each button and have provided onClick handler function calls to each onClick prop.

Filtering the list

Inside our handleFilter() function we do the work of filtering our List component.

    const handleFilter = () => {
       const updatedList = List.filter(list => {
            if(list.Year < 2000) {  
                return
            }
            return list
        })
        
        setNewList(updatedList.map(list => (
            <li key={list.id}>
                <span className='author'>{list.Author} - </span>
                <span className='title'>{list.Title} - </span>
                <span className='year'>{list.Year} </span>
            </li>
        ))
            
        )
        setNewTitle("Novel's that won after the year 2000")
    }

We are assigning the value of the filtered list to the updatedList variable. We are doing an early return for any novels awarded before the year 2000. And finally we return the list, or what is left from being filtered out. In our setNewList() function we are mapping through the updatedList variable to update the state of the newList element.

Sorting the list

Our handleSort() function assigns the value of the sorted List to the updatedList variable and we then map through the updatedList inside of our setNewList piece of state. It’s practically the same as the handleFilter() function above.

    const handleSort = () => {
        const updatedList = List.sort((a, b) => a.Author > b.Author ? 1 : -1)
        setNewList(updatedList.map(list => (
            <li key={list.id}>
                <span className='author'>{list.Author} - </span>
                <span className='title'>{list.Title} - </span>
                <span className='year'>{list.Year} </span>
                </li>
        ))
        )
        setNewTitle("Author's sorted by Author first name")
    }

This sort function takes a as the first element to compare and b as the second. If a.Author is greater than b.Author return 1 otherwise return -1. This sorts the array by Author first name.

Checking the contents of the list with some()

The Array.some() function will return a boolean value. Either what you’re checking for exists in the list somewhere (one or more times) or it doesn’t. I’m checking to see if my favorite author, Ursula K. Le Guin, is in this list.

To do that, I assign the value of the list checked with the some function to the updatedList variable. Then if updatedList is true, I set the state of the setNewList to some JSX.

    const handleSome = () => {
        const updatedList = List.some(list => {
            const ursula = list.Author === 'Ursula K. Le Guin'
            return ursula
        })
        if(updatedList){
        setNewList([<span>'Author by the name Ursula K. Le Guin exists in the list'</span>])
        }
        setNewTitle("Does an Author by the name Ursula K. Le Guin exist in the list?")
    }

Conclusion

Hopefully now you have some idea of ways to integrate array methods into your React application. We covered how to use Array.filter() in React, how to use Array.sort() in React, and how to use Array.some() in React!

Photo by Pawel Czerwinski on Unsplash