Updating Elements in an Array

Learn Updating Elements in an Array with practical examples, explanations, best practices, and real-world coding techniques.

What Is Array Updating?

Array updating means changing the value of an existing element without necessarily changing the size or structure of the array. In most cases, an element is updated by identifying its index and assigning a new value.

Updating is different from inserting and deleting. Insertion adds a new element, deletion removes an existing element, while updating replaces the value stored at an existing position.

const scores = [80, 75, 90];

scores[1] = 85;

console.log(scores);
// [80, 85, 90]

Updating an Element Using Its Index

The simplest way to update an array element in JavaScript is to assign a new value to a specific index.

const languages = ['JavaScript', 'Python', 'Java'];

languages[1] = 'C#';

console.log(languages);
// ['JavaScript', 'C#', 'Java']

Because the index directly identifies the position, updating an existing element by index is typically an O(1) operation.

Updating the First or Last Element

The same technique can be used for elements at any valid index, including the first and last positions.

const numbers = [10, 20, 30, 40];

numbers[0] = 5;
numbers[numbers.length - 1] = 45;

console.log(numbers);
// [5, 20, 30, 45]

Updating Multiple Elements

When several elements need to be updated according to a rule, traversal can be combined with direct index assignment.

For example, suppose every price needs to be increased by 10 percent:

const prices = [100, 200, 300];

for (let i = 0; i < prices.length; i++) {
  prices[i] = prices[i] * 1.10;
}

console.log(prices);
// [110, 220, 330]

Since every element is visited once, updating all n elements takes O(n) time.

Conditional Array Updates

Sometimes only elements that satisfy a particular condition should be changed. A conditional statement can be used during traversal to identify those elements.

const scores = [45, 72, 38, 91, 56];

for (let i = 0; i < scores.length; i++) {
  if (scores[i] < 50) {
    scores[i] = 50;
  }
}

console.log(scores);
// [50, 72, 50, 91, 56]

This pattern is useful when an application needs to enforce a minimum value, normalize data, or correct values that fall outside an expected range.

Updating an Array with map()

The map() method creates a new array by applying a transformation to every element. It is useful when you want to produce an updated collection without modifying the original array.

const prices = [100, 200, 300];

const updatedPrices = prices.map(price => price * 1.10);

console.log(prices);
// [100, 200, 300]

console.log(updatedPrices);
// [110, 220, 330]

This approach is often preferred when working with application state because it creates a new array instead of changing the existing reference.

Updating Objects Inside an Array

Arrays frequently contain objects. In this situation, updating an element usually means changing one or more properties of an object.

const users = [
  { id: 1, name: 'Alice', active: true },
  { id: 2, name: 'Bob', active: false }
];

users[1].active = true;

console.log(users);
// [
//   { id: 1, name: 'Alice', active: true },
//   { id: 2, name: 'Bob', active: true }
// ]

This directly modifies the object stored inside the array. Whether this is appropriate depends on how the surrounding application manages state.

Updating an Object Immutably

When an application follows immutable data patterns, a new array and a new object can be created instead of modifying the existing values.

const users = [
  { id: 1, name: 'Alice', active: true },
  { id: 2, name: 'Bob', active: false }
];

const updatedUsers = users.map(user =>
  user.id === 2
    ? { ...user, active: true }
    : user
);

console.log(updatedUsers);

The original users array remains unchanged, while updatedUsers contains the modified object.

Finding an Element Before Updating

In many applications, the index is not known in advance. The program may first need to find an element based on a value or condition and then update it.

const numbers = [10, 20, 30, 40];

const index = numbers.indexOf(30);

if (index !== -1) {
  numbers[index] = 35;
}

console.log(numbers);
// [10, 20, 35, 40]

Finding the element using a linear search takes O(n) time in the general case. Once the index is known, the actual update is typically O(1).

Updating Based on an Object Property

For arrays of objects, a common requirement is to update the object that matches a specific identifier.

const products = [
  { id: 101, name: 'Laptop', stock: 10 },
  { id: 102, name: 'Mouse', stock: 25 },
  { id: 103, name: 'Keyboard', stock: 15 }
];

const product = products.find(item => item.id === 102);

if (product) {
  product.stock = 30;
}

console.log(products);

The find() operation may inspect multiple elements before finding the requested object, so the search is typically O(n).

Updating Without Changing Array Length

A standard update replaces a value at an existing index and therefore keeps the number of elements unchanged.

const colors = ['red', 'green', 'blue'];

colors[1] = 'yellow';

console.log(colors);
// ['red', 'yellow', 'blue']

console.log(colors.length);
// 3

This is different from methods such as push(), pop(), shift(), and splice(), which can change the size of an array.

Updating an Array Using splice()

The splice() method can replace one or more elements at a specific position. Unlike direct assignment, it can also change the array's length depending on how it is used.

const numbers = [10, 20, 30, 40];

numbers.splice(1, 1, 25);

console.log(numbers);
// [10, 25, 30, 40]

Here, one element starting at index 1 is removed and replaced with 25. Because elements may need to move, the operation can require O(n) time.

Updating Every Element

When every element must be transformed, map() is often a clear choice because the operation expresses the intent directly: create a new value for each existing element.

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

const squared = numbers.map(number => number * number);

console.log(squared);
// [1, 4, 9, 16, 25]

Transforming every element requires visiting the complete array, so the time complexity is O(n).

Direct Update vs Immutable Update

Approach Example Original Array
Direct update arr[2] = 50 Modified
Immutable update arr.map(...) Preserved

Direct updates are straightforward and efficient when modifying the existing collection is appropriate. Immutable updates are useful when predictable state changes and reference replacement are important, such as in many frontend application architectures.

Time Complexity of Array Updates

Update Operation Typical Time
Update known index O(1)
Update every element O(n)
Find then update O(n) typical
Replace using splice() O(n) typical

Common Mistakes

  • Using an incorrect index when updating an element.
  • Forgetting that JavaScript arrays use zero-based indexing.
  • Confusing updating an element with inserting a new element.
  • Using a full traversal when the index is already known.
  • Modifying an array while iterating without considering how the changes affect later indexes.
  • Assuming map() modifies the original array; it returns a new array instead.
  • Using splice() when a simple direct assignment would be sufficient.

Key Takeaways

  • Array updating means replacing existing element values.
  • Updating a known index is typically an O(1) operation.
  • Updating every element requires O(n) time.
  • Searching for an element before updating adds the cost of the search.
  • map() is useful for creating an updated array without modifying the original.
  • splice() can replace elements but may require shifting and is generally O(n).
  • The best update technique depends on whether the original array should be modified and whether the index is already known.

Code Examples

const scores = [80, 75, 90, 85];

scores[1] = 82;

console.log(scores);
// [80, 82, 90, 85]
    
const scores = [45, 72, 38, 91, 56];

for (let i = 0; i < scores.length; i++) {
  if (scores[i] < 50) {
    scores[i] = 50;
  }
}

console.log(scores);
// [50, 72, 50, 91, 56]
    
const prices = [100, 200, 300];

const updatedPrices = prices.map(price => price * 1.10);

console.log(prices);
// [100, 200, 300]

console.log(updatedPrices);
// [110, 220, 330]
    
const users = [
  { id: 1, name: 'Alice', active: true },
  { id: 2, name: 'Bob', active: false }
];

const updatedUsers = users.map(user =>
  user.id === 2
    ? { ...user, active: true }
    : user
);

console.log(updatedUsers);
    

Pro Tip

If you already know the index of the element you want to change, direct assignment is usually the simplest and most efficient approach. If you need to transform an entire collection or preserve the original array, consider map().

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.