DEV Community

Cover image for Find and Replace elements in Array with JavaScript
AlbertoM
AlbertoM

Posted on • Updated on • Originally published at inspiredwebdev.com

Find and Replace elements in Array with JavaScript

This article was originally posted on my blog. Head over to inspiredwebdev.com for more articles and tutorials. Check out my JavaScript course on Educative to learn everything from ES6 to ES2020.

 

Arrays are a very common data structure and it's important to know how to manipulate them by retrieving, adding, and replacing data inside of them.

In this article, we are going to learn what are the different ways to find and replace items inside of arrays.

 

Check that an Array contains a value

First, let's look at different ways of checking if our Array includes a certain value provided.

We can do that in different ways such as:

const arr = [1,2,3,4,5];

arr.includes(2);
// true
arr.includes(6);
// false
Enter fullscreen mode Exit fullscreen mode

Array.includes is probably the easiest method to remember and it will return us true or false if our Array includes or not the value we passed.

This method can take an additional argument which defines the index from where we want to start looking, leave empty if you want to check the whole Array.

Let's continue with more methods:

const arr = [1,2,3,4,5];

!!arr.find((a) => a === 2);
// true
!!arr.find((a) => a === 6);
// false
Enter fullscreen mode Exit fullscreen mode

Array.find is also another method we can use to check if our Array contains a certain value.

This method will return the value itself or undefined if no value is found so we can use the !! operator to convert the result to boolean and quickly see if there's a match or not.

It's a more powerful method compared to Array.includes as we can pass a callback to it, not just a value to check, meaning that we can do more complex checks such as:

const arr = [1,2,3,4,5];

!!arr.find((a) => a > 2 && a < 4);
// true
Enter fullscreen mode Exit fullscreen mode

Being able to pass a callback to it it means that unless your check is a very straightforward one, you are most likely going to use find over includes.

You can pass a second argument to the callback function defining the starting point where to start checking, leave empty to check the whole Array.

Next up we have Array.indexOf and Array.findIndex:

const arr = [1,2,3,4,5];

arr.indexOf(1) !== -1;
// true
arr.indexOf(6) !== -1;
// false

arr.findIndex((el) => el === 1) !== -1;
// true
arr.findIndex((el) => el === 6) !== -1;
// false
Enter fullscreen mode Exit fullscreen mode

Array.indexOf and Array.findIndex are similar because they both return the index of the first matching element found in our Array, returning us -1 if it's not found.

To check if an element exists, we simply need to check if the returned value is -1 or not.

These methods are useful because they can be used to both checks if an element exists in the Array while at the same time getting a reference as to where that element is positioned, which we can use to then replace that said element.

The difference between the two methods is the same as the one we saw between Array.includes and Array.find, where the first one (Array.indexOf) will accept a value to check whereas the second one (Array.findIndex) will accept a callback to perform more advanced checks.

Similarly to all the methods we previously saw, you can also define a starting index where to start check the Array.

Next up are two new metho introduced in ES6 (ES2015):

const arr = [1,2,3,4,5];

arr.some((el) => el === 2);
// true
arr.every((el) => el === 3);
// false
Enter fullscreen mode Exit fullscreen mode

Array.some will check if at least one value in the array matches the condition in our callback function and Array.every will check that ALL of the elements in the Array match that condition.

 

Replacing an element of an Array at a specific index

Now that we know how to check if the Array includes a specific element, let's say we want to replace that element with something else.

Knowing the methods above, it couldn't be easier!

In order to replace an element we need to know its index, so let's see some examples using the methods we just learned:

const arr = [1,2,3,4,5];

const index = arr.indexOf(2);
arr[index] = 0;
arr;
// [1,0,3,4,5];
Enter fullscreen mode Exit fullscreen mode

As you can see, first, we got the index of the element we wanted to change, in this case, the number 2 and then we replaced it using the brackets notation arr[index].

We can do the same using findIndex:

const arr = [1,2,3,4,5];

const index = arr.findIndex((el) => el === 2);
arr[index] = 0;
arr;
// [1,0,3,4,5];
Enter fullscreen mode Exit fullscreen mode

Pretty easy right? Using findIndex we can also check scenarios like the following where we have an Array of Objects:

const arr = [
    {
        id:1,
        val: 'one'
    },
    {
        id:2,
        val: 'two'
    },
    {
        id:3,
        val: 'three'
    },
    {
        id:4,
        val: 'four'
    },
    {
        id:5,
        val: 'five'
    },
];

const index = arr.findIndex((el) => el.id === 2);
arr[index] = {
    id:0,
    val: 'zero'
};
arr;
// [
//     {
//         id:1,
//         val: 'one'
//     },
//     {
//         id:0,
//         val: 'zero'
//     },
//     {
//         id:3,
//         val: 'three'
//     },
//     {
//         id:4,
//         val: 'four'
//     },
//     {
//         id:5,
//         val: 'five'
//     },
// ];
Enter fullscreen mode Exit fullscreen mode

As you can see, using findIndex we can easily find and then replace Objects in an Array of Objects.

Let's say we are not interested in replacing a value but we just want to remove it, we will now look at different ways of doing so.

&bnbsp;

Removing a value from an Array

First, let's look at the more basic methods to remove values from an Array: Array.pop and Array.shift

const arr = [1,2,3,4,5];
arr.pop();
arr;
// [1,2,3,4]

const arr2 = [1,2,3,4,5];
arr2.shift();
arr2;
// [2,3,4,5];
Enter fullscreen mode Exit fullscreen mode

Array.pop will remove the last element of the Array while Array.shift will remove the first one. No additional arguments are allowed, so you can see that these methods are fairly basic.

Both methods will modify your origianl array and both return the removed element so you can do the following:

const arr = [1,2,3,4,5];
const el = arr.pop();
el;
// 1
Enter fullscreen mode Exit fullscreen mode

Now we will look at a couple of ways to remove a specific element from an array.

First, let's look at Array.splice used in combination with Array.indexOf.

Array.splice allows us to remove elements from an Array starting from a specific index. We can provide a second argument to specify how many elements to delete.

const arr = [1,2,3,4,5];
const index = arr.indexOf(2);

arr.splice(index,1);
arr;
// [1,3,4,5];

const arr2 = [1,2,3,4,5];
const index = arr2.indexOf(2);

arr2.splice(index);
arr2;
// [1]
Enter fullscreen mode Exit fullscreen mode

As you can see, in the first example we specified 1 as the number of elements to remove, whereas in the second example we didn't pass any argument thus removing all items in the array from our starting index.

Array.splice will modify your original array and return the removed elements so you can do the following:

const arr = [1,2,3,4,5];
const index = arr.indexOf(2);

const splicedArr = arr.splice(index,1);
arr;
// [1,3,4,5];

splicedArr;
// [2]
Enter fullscreen mode Exit fullscreen mode

Next up, we can also remove elements from an array based on a condition and not just on an index with the use of Array.filter:

let arr = [1,2,3,4,5];
const newArr = arr.filter((el) => el >2);

newArr;
// [3,4,5]
arr;
// [1,2,3,4,5];
Enter fullscreen mode Exit fullscreen mode

Differently from Array.pop, Array.shift and Array.splice , Array.filter creates a new array with all the elements that pass the condition in the callback function so your original array won't get modified as you can see from the code above.

In this case, our new Array consisted of all the elements of the original that are greater than 2.


Thank you very much for reading. Follow me on DevTo or on my blog at inspiredwebdev or on twitter. Check out Educative.io for interactive programming courses.

Disclaimer: Links to Amazon and Educative are affiliate links, purchases you make will generate extra commissions for me. Thank you


book banner

Get my ebook on Amazon and Leanpub

Top comments (12)

Collapse
 
wulymammoth profile image
David

Hey man -- the first section with regards to removing items from an array appears to be incorrect as Array.prototype.pop() and Array.prototype.shift() do opposite of what you say. The comment showing the results also appear to be incorrect. I believe the they should be:

Your current code:

const arr = [1,2,3,4,5];
arr.pop();
arr;
// [1,2,3,4]

const arr2 = [1,2,3,4,5];
arr2.shift();
arr2;
// [1,2,3,4];

Corrected code:

const arr = [1,2,3,4,5];
arr.pop(); // 5
arr; // [1,2,3,4]

const arr2 = [1,2,3,4,5];
arr2.shift(); // 1
arr2; // [2,3,4,5]

I think it's also worth noting, when introducing these topics, that there are Array methods that are mutable and others that are not (return new data structures). A lot of the ones that you've mentioned here mutate the original array. There are some tricky situations that people run into if they aren't aware of these behaviors. I know that you somewhat note that when presenting Array.prototype.filter, but it would be useful to show that the original array is left unchanged. I mention this because modern JavaScript adopts a lot of functional programming constructs, like immutable data types, that reduce bugs in code (e.g. React, Redux with ImmutableJS). To return a new data structure each time, I typically end up using Array.prototype.reduce. This is one of my most used functions or methods in various programming languages.

Otherwise, nice write-up! :)

Collapse
 
albertomontalesi profile image
AlbertoM

Awesome find, thanks for catching that error. Also thanks for the feedback, I'll try to expand on the explanation of each method :)

Collapse
 
uniqcoda profile image
Mary Etokwudo

This has been very helpful. Especially this part "Replacing Items in an Array of Objects". I am building a project in React and I needed to set the state of an array of objects when one element changes

Collapse
 
albertomontalesi profile image
AlbertoM

Awesome! I'm happy it helped

Collapse
 
ahirrea profile image
Ahirrea

Array.prototype.splice is really cool. I think it's worth to mention that you actually can do a replace with a third argument:

const arr = [1,2,3,4,5];
arr.splice(1, 1, 0);
arr;
// [1,0,3,4,5]

Collapse
 
rajoyish profile image
Rajesh Budhathoki • Edited

"Array.pop" removes last or first? Please update the post, it's very hard to comprehend which one is which for a newbie like me. I figured out after going through MDN. Thanks for the effort.

Collapse
 
albertomontalesi profile image
AlbertoM

You are correct, i should have spellchecked my article more thoroughly. The example was correct, the text was saying the opposite

Collapse
 
sumerokr profile image
Aleksandr Sadykov • Edited

Array.find will not return a Boolean value in your examples. Instead the value itself will be returned. Or the undefined, if there is no match.

Collapse
 
albertomontalesi profile image
AlbertoM

You are perfectly right, i've updated the text

Collapse
 
raounek profile image
touibeg mohamed

good job ...

Collapse
 
geoffhom profile image
Geoffrey Hom

I'm annoyed I had to create an account to help you guys out. That's not a knock on you but those who manage this site.

"Ass you can see," search for that in your article. I think you mean "As…"?

Collapse
 
maxdevjs profile image
maxdevjs

That's a nice one, I am late so only have origianl -> original