Horje
JavaScript Array with() Method

The with() method in JavaScript Array returns a new array with the element at the given index replaced with the given value.

Syntax:

input_array.with(index, value)

Parameters:

  • Index: RangeError is thrown if the provided index does not exist in the array.
  • value: It is the value that is assigned to the specified index position.

Example 1: Consider a JavaScript array with 5 elements and replace the value present at Index position – 4 with 100.

JavaScript
let actual_array = [60, 78, 90, 34, 67];
console.log("Existing Array: ", actual_array);

// with()
let final_array = actual_array.with(4, 100);
console.log("Final Array: ", final_array);

Output:

Existing Array:  [60, 78, 90, 34, 67]
Final Array: [60, 78, 90, 34, 100]

Example 2: Let’s apply map() function to this function and replace the element present at index – 4 with 100 multiplied by 2.

JavaScript
let actual_array = [60, 78, 90, 34, 67];
console.log("Existing Array: ", actual_array);

// with()
let final_array = actual_array
    .with(4, 100)
    .map((x) => x * 2);
console.log("Final Array: ", final_array);

Output:

Existing Array:  [60, 78, 90, 34, 67]
Final Array: [60, 78, 90, 34, 200]



Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Filter an Array in JavaScript ? How to Filter an Array in JavaScript ?
JavaScript Program for nth Term of Geometric Progression JavaScript Program for nth Term of Geometric Progression
How to Convert String to Array of Objects JavaScript ? How to Convert String to Array of Objects JavaScript ?
How to Check Presence of a Specific Object Property in an Array ? How to Check Presence of a Specific Object Property in an Array ?
How to get Matching Data from a Prompt on an Existing Object ? How to get Matching Data from a Prompt on an Existing Object ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13