Change array elements javascript

How to replace elements in array with elements of another array in JavaScript?

The given task is to replace the elements in an array with elements of another array.

Input-Output Scenario

Let’s look into some input-output scenarios. Consider there are there two arrays with elements in it. The first array is having more elements than the second array and we are replacing a part of elements in the first array with the elements from second array.

Array1 = [1, 3, 5, 7, 2, 4]; Array2 = [3, 6]; Output = [3, 6, 5, 7, 2, 4] // elements got replaced

Let’s consider another scenario, where the elements in the first array are more than the elements in second array. The second array elements will fill the first array.

Array1 = [3, 6]; Array2 = [1, 3, 5, 7, 2, 4]; Output = [1, 3, 5, 7, 2, 4]

Using Splice() method

The splice() method will modify or change the items of an array by replacing or removing the elements and also adding elements.

Syntax

Following is the syntax of splice() method,

splice(start, deleteCount, item1, item2, itemN)

We can use the splice() method to replace a part of array elements with elements from another array. But in this scenario we need to pass the elements as parameters, not the array as parameter.

Читайте также:  Python команда input print

To achieve the above task splice() method except the parameters like (0, anotherArr.Length, 1, 2, 3). We need to create an array with the above parameters and use the apply method to call the splice method with parameters. We also use concat() method to concat both the arrays.

Below is the syntax for the above excepted parameters,

Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr));

Example 1

Following is an example to replace elements in one array with elements from another array −

!DOCTYPE html> html> head> title>Replace elements in array with elements of another array/title> /head> center> body> p id = "para1">/p> p id = "para2">/p> button onClick="fun()"> Click to replace elements/button> h3 id="demo">/h3> script> var arr = ["Sharukh","Khan","toh", "suna", "hoga"]; document.getElementById("para1").innerHTML = arr; var anotherArr = [ "Rahul", "naam" ]; document.getElementById("para2").innerHTML = anotherArr; function fun() Array.prototype.splice.apply(arr, [0, anotherArr.length].concat(anotherArr)); document.getElementById("demo").innerHTML = arr; >; /script> /body> /center> /html>

In the above output, we’ve given arr as first parameter where the [0, anotherArr.length] (all the elements) in second array will replace from the starting index of first array and the concat() method will concat both the arrays.

Example 2

In the example below, we have created two arrays. The first is more elements than the elements in the second array. by using splice() method we have set the index as 0 and passed arr2.length and extacted them with spread(…) operator so the elements will be replaced from 0th index of arr1.

!DOCTYPE html> html> head> title>Replace elements in array with elements of another array/title> /head> center> body> p id = "para1">/p> p id = "para2">/p> button onClick="func()"> Click to replace elements/button> h3 id="demo">/h3> script> let arr1 = [6, 31, 8, 21, 20 , 22]; document.getElementById("para1").innerHTML = arr1; let arr2 = ["hello", "numbers"]; document.getElementById("para2").innerHTML = arr2; function func() arr1.splice(0, arr2.length, . arr2); document.getElementById("demo").innerHTML = arr1; >; /script> /body> /center> /html>

As we can see in the output, the elements got replaced in the first array.

Example 3

In the following example, we have two arrays. The elements in the first array is lesser than the elements in the second array. we have replaced the elements by using splice method. The elements of second array will fill the entire first array because the size of elements in first array is lesser than the second array.

!DOCTYPE html> html> head> title>OReplace elements in array with elements of another array/title> /head> center> body> p id = "para1">/p> p id = "para2">/p> button onClick="func()"> Click to replace elements/button> h3 id="demo">/h3> script> let arr1 = [6, 31]; document.getElementById("para1").innerHTML = arr1; let arr2 = [66, 88, 23, 53, 54]; document.getElementById("para2").innerHTML = arr2; function func() arr1.splice(0, arr2.length, . arr2); document.getElementById("demo").innerHTML = arr1; >; /script> /body> /center> /html>

In the output, we can see that the elements in the second array replaced and filled the first array.

Источник

Change array elements 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.

Источник

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