Javascript заменить значения элементов массива

Find and Replace elements in Array with JavaScript

Check out my Github for my free-to-read JavaScript Ebook that covers all the new features from ES6 to 2021. If you want find a great place for interactive tutorials, i recommend Educative where you can find my JavaScript course
This website contains affiliate links.

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

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

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

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

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

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];

Ass 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];

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' // >, // ];

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.

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];

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

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]

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]

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];

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.

Источник

Javascript заменить значения элементов массива

Last updated: Dec 22, 2022
Reading time · 5 min

banner

# Table of Contents

# Replace an Element in an Array in JavaScript

To replace an element in an array:

  1. Use the Array.indexOf() method to get the index of the element.
  2. Change the value of the element at the specific index.
  3. The value of the array element will get updated in place.
Copied!
const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 if (index !== -1) arr[index] = 'z'; > console.log(arr); // 👉️ ['z', 'b', 'c']

We used the Array.indexOf method to get the index of the array element with a value of a .

Copied!
const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); console.log(index); // 👉️ 0

We then replaced the element at that index with a new value.

Copied!
const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 if (index !== -1) arr[index] = 'z'; > console.log(arr); // 👉️ ['z', 'b', 'c']

We check if the method didn't return an index of -1 to be sure that an element with the specified value exists.

JavaScript indexes are zero-based, so the first element in an array has an index of 0 and the last element has an index of arr.length - 1 .

Alternatively, you can use the Array.splice() method.

# Replace an Element in an Array using Array.splice()

This is a three-step process:

  1. Use the indexOf() method to get the index of the element to be replaced.
  2. Use the Array.splice() method to replace the element at the specific index.
  3. The array element will get replaced in place.
Copied!
const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 arr.splice(index, 1, 'z'); console.log(arr); // 👉️ [ 'z', 'b', 'c' ]

We passed the following 3 arguments to the Array.splice method:

  1. start index - the index at which to start changing the array.
  2. delete count - how many elements should be deleted from the array.
  3. item1 - the item to add to the array.

We set the start index to the index of the array element we want to replace.

Copied!
const arr = ['a', 'b', 'c']; const index = arr.indexOf('a'); // 👉️ 0 arr.splice(index, 1, 'z'); console.log(arr); // 👉️ [ 'z', 'b', 'c' ]

We set the delete count argument to 1 , so the Array.splice() method will remove the array element at the specified index and will add the provided third argument at the same index.

In practice, we remove the array element at the specified index and then insert a different value at the same index, so we end up replacing the array element.

An alternative approach is to use a basic for loop.

# Replace an Element in an Array using a for loop

This is a three-step process:

  1. Use a for loop to iterate for array.length iterations.
  2. Check if each array element is the one to be replaced.
  3. If the condition is met, replace the element at the index and break out of the for loop.
Copied!
const arr = ['a', 'b', 'c']; for (let index = 0; index arr.length; index++) if (arr[index] === 'a') arr[index] = 'z'; break; > > console.log(arr); // 👉️ ['z', 'b', 'c']

We used a basic for loop to iterate over the array. On each iteration, we check if the current element is the one we want to replace.

Once we find and replace the element, we break out of the loop to avoid unnecessary work.

If you want to replace all array elements with the specified value, simply remove the break statement.

Copied!
const arr = ['a', 'b', 'c', 'a', 'a']; for (let index = 0; index arr.length; index++) if (arr[index] === 'a') arr[index] = 'z'; > > console.log(arr); // 👉️ [ 'z', 'b', 'c', 'z', 'z' ]

We didn't use a break statement, so we replaced all elements with a value of a with elements with a value of z .

An alternative solution is to not change the original array, but instead, create a new array containing the desired values.

Want to learn more about updating arrays in JavaScript ? Check out these resources: Update all Elements in an Array in JavaScript ,Update an Object's Property in Array of Objects in JS.

We can use the Array.map() method to achieve this.

# Replace an Element in an Array using Array.map()

This is a three-step process:

  1. Use the Array.map() method to iterate over the array.
  2. Check if the current element is the one to be replaced.
  3. If the condition is met, return the replacement value, otherwise, return the original value.
Copied!
const arr = ['a', 'b', 'c']; const newArr = arr.map(element => if (element === 'a') return 'z'; > return element; >); console.log(newArr); // 👉️ ['z', 'b', 'c'] console.log(arr) // 👉️ ['a', 'b', 'c']

The function we passed to the Array.map() method gets called with each element in the array.

In the example, we replace all array elements with a value of a , setting them to a value of z .

We didn't change the contents of the original array and instead created a new array with the values we need. This is often easier to reason about and track in larger code bases.

You can also use the Array.forEach() method to replace the array elements in place.

# Replace an Element in an Array using Array.forEach()

This is a three-step process:

  1. Use the Array.forEach() method to iterate over the array.
  2. Check if each element is the one to be replaced.
  3. If the condition is met, replace the element with the replacement value.
Copied!
const arr = ['a', 'b', 'c', 'a', 'a']; arr.forEach((element, index) => if (element === 'a') arr[index] = 'z'; > >); // 👇️ [ 'z', 'b', 'c', 'z', 'z' ] console.log(arr);

The function we passed to the Array.forEach() method gets called with each element in the array.

On each iteration, we check if the current element is the one to be replaced.

If the condition is met, we replace the element with the replacement value.

The forEach() method is useful if you need to replace all occurrences of the value in the array.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью