How to Manipulate Arrays in React

In this tutorial I will try and teach you a few methods you can use to perform some array manipulation using JavaScript methods in a React project. It assumes you have some familiarly with React and JavaScript. The example project itself is made with create react app and you can view the full source here. There is also a video for more support.

We will take an array with randomly generated values and then perform several common JavaScript array manipulation methods on it. Let’s Go!

 NOTE: Refer to the main component on GitHub for guidance on overall structure.

Generate Random Values for an Array 

First, we are going to need some values in our array to manipulate. In this example I have created a for loop, generated a number 1-10 and then pushed to the “arr” array before finally setting the state of “arr” after the loop has executed. In the example code you can see I bound this to an onclick of a button, but you could also set it to run in componentDidMount() if you wish to set it when the component mounts.

generateRandNum(){
    let i;
    let arr=[];
    for (i = 0; i < 10; i++) {
        let randomNum = Math.floor(Math.random() * 10);
        arr.push(randomNum);
    }
    this.setState({arr:arr})
}

Methods

Ok, so now we have our first array in our React project. We can look at a few example methods we can perform on it.

Push

Definition: The push() method adds zero or more elements to the end of an array and returns the new length of the array.

In this example I decided to generate a random number again and add it to the end of our “arr” array on a click of a button. I also utilise the slice() method in this example to create a copy of the original array and then add the new random item to the end of it.

addRandomValuePush(){
    let randomNum = Math.floor(Math.random() * 10);
    let newArray = this.state.arr.slice();
    newArray.push(randomNum);
    this.setState({arr:newArray});
}

Reference an Array Index

Another quite common thing we will need to do with arrays is to reference a specific index of an item in an array. It can be confusing at first because the index of an array starts at 0 as opposed to 1, so for example if we had the following array:

let array = ['Ben', 'John', 'Craig'];

the index of each item would be:

  • Ben – 0
  • John – 1
  • Craig – 2

NOT:

  • Ben – 1
  • John – 2
  • Craig – 3

The following code is how we will reference a specific item at an index (in this example being displayed between paragraph tags).

<p>{this.state.arr[0]}</p>

Display the Length of the Array

Sometimes we may want to show or find the length of an array object we have in our array. We can simply use the .length property to find this out, like so:

<p>{this.state.arr.length}</p>

Map Method

map() can be a useful method to use if you want to modify the original array and create a new one. In this example, I take the original array and use the map function to multiply the values of the array items by two and then set the state of the 2nd array to the multiplied values. The following code block achieves this:

mapArr(){
    let arr = this.state.arr.slice();
    let arr2 = arr.map(x => x*2);
    this.setState({arr2:arr2});
}

Filter Method

Finally the filter() method can be useful if you want to check for some conditional values with your array and create a new array based on them (“arr3″ in this example). In this example I take the 10 randomly generated values and create a new array with only the values in the original array which are over 5.

filter(){
    let arr = this.state.arr.slice();
    let result = arr.filter(item => item>5);
    this.setState({arr3:result});
}

Ok, so that is a bit of an introduction to some array manipulation methods you can use in JavaScript in React. There are many more you can explore.

Further Reading:

2
0

Related Posts