Skip to content

replace

Replace the first element in an array that matches the condition.

Basic Usage

typescript
import { replace } from 'radash'

const users = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
]

const updatedUsers = replace(
  users,
  { id: 2, name: 'Bob', age: 31 }, // new data
  user => user.id === 2 // matching condition
)
// [
//   { id: 1, name: 'Alice', age: 25 },
//   { id: 2, name: 'Bob', age: 31 }, // updated
//   { id: 3, name: 'Charlie', age: 35 }
// ]

Syntax

typescript
function replace<T>(
  array: readonly T[],
  item: T,
  matcher: (item: T, index: number, array: readonly T[]) => boolean
): T[]

Parameters

  • array (readonly T[]): The array to operate on
  • item (T): The new element to replace with
  • matcher (function): Function to match elements
    • item (T): Current element
    • index (number): Index of the current element
    • array (readonly T[]): The original array

Return Value

Returns a new array containing the replaced element. If no matching element is found, returns the original array.

Examples

Replacing Existing Elements

typescript
import { replace } from 'radash'

const products = [
  { id: 1, name: 'Laptop', price: 999 },
  { id: 2, name: 'Phone', price: 599 },
  { id: 3, name: 'Tablet', price: 399 }
]

const updatedProducts = replace(
  products,
  { id: 2, name: 'Phone', price: 549 }, // price reduced
  product => product.id === 2
)
// [
//   { id: 1, name: 'Laptop', price: 999 },
//   { id: 2, name: 'Phone', price: 549 }, // updated
//   { id: 3, name: 'Tablet', price: 399 }
// ]

Replacing Simple Values

typescript
import { replace } from 'radash'

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

const updatedNumbers = replace(numbers, 10, num => num === 3)
// [1, 2, 10, 4, 5] // 3 replaced with 10

const words = ['hello', 'world', 'javascript']
const updatedWords = replace(words, 'typescript', word => word === 'javascript')
// ['hello', 'world', 'typescript'] // javascript replaced with typescript

Using Index Matching

typescript
import { replace } from 'radash'

const items = ['a', 'b', 'c', 'd']

const updatedItems = replace(items, 'x', (_, index) => index === 1)
// ['a', 'x', 'c', 'd'] // element at index 1 replaced with 'x'

Replacing Non-existent Elements

typescript
import { replace } from 'radash'

const fruits = ['apple', 'banana', 'cherry']

const updatedFruits = replace(fruits, 'orange', fruit => fruit === 'grape')
// ['apple', 'banana', 'cherry'] // grape not found, returns original array

Replacing Elements in Object Arrays

typescript
import { replace } from 'radash'

const users = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob', email: 'bob@example.com' },
  { id: 3, name: 'Charlie', email: 'charlie@example.com' }
]

const updatedUsers = replace(
  users,
  { id: 2, name: 'Bob', email: 'bob.new@example.com' },
  user => user.id === 2
)
// [
//   { id: 1, name: 'Alice', email: 'alice@example.com' },
//   { id: 2, name: 'Bob', email: 'bob.new@example.com' }, // email updated
//   { id: 3, name: 'Charlie', email: 'charlie@example.com' }
// ]

Replacing Nested Objects

typescript
import { replace } from 'radash'

const config = {
  settings: {
    theme: 'dark',
    language: 'en',
    notifications: true
  },
  users: [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' }
  ]
}

const updatedConfig = replace(
  config.users,
  { id: 2, name: 'Bob Updated' },
  user => user.id === 2
)
// Replaced the Bob object in the users array

Handling Conditional Replacement

typescript
import { replace } from 'radash'

const scores = [85, 92, 78, 96, 88]

// Replace the first score below 80
const updatedScores = replace(scores, 80, score => score < 80)
// [85, 92, 80, 96, 88] // 78 replaced with 80

// Replace the first even number
const numbers = [1, 3, 4, 7, 9]
const updatedNumbers = replace(numbers, 0, num => num % 2 === 0)
// [1, 3, 0, 7, 9] // 4 replaced with 0

Using in State Management

typescript
import { replace } from 'radash'

interface Todo {
  id: number
  text: string
  completed: boolean
}

const todos: Todo[] = [
  { id: 1, text: 'Learn React', completed: false },
  { id: 2, text: 'Build app', completed: false },
  { id: 3, text: 'Deploy', completed: false }
]

// Mark todo as completed
const toggleTodo = (todoId: number) => {
  return replace(todos, 
    { id: todoId, text: 'Learn React', completed: true },
    todo => todo.id === todoId
  )
}

const updatedTodos = toggleTodo(1)
// First todo marked as completed

Handling Duplicate Elements in Arrays

typescript
import { replace } from 'radash'

const items = ['apple', 'banana', 'apple', 'cherry']

// Replace the first 'apple'
const updatedItems = replace(items, 'orange', item => item === 'apple')
// ['orange', 'banana', 'apple', 'cherry'] // only replace the first apple

Notes

  1. Keep original array unchanged: replace does not modify the original array, but returns a new array
  2. Only replace first match: If there are multiple matching elements, only the first one is replaced
  3. No match found: If no matching element is found, returns the original array
  4. Performance: Time complexity is O(n), where n is the array length
  5. Matcher function: The matcher function should return a boolean value

Differences from Other Methods

  • map(): Processes all elements, not just the first matching one
  • filter(): Only filters elements, cannot replace
  • replace(): Specifically designed for replacement operations
  • splice(): Modifies the original array, while replace returns a new array
  • replaceOrAppend(): Appends if no match is found, while replace only replaces

Practical Application Scenarios

  1. User management: Update user information
  2. Product management: Update product prices or information
  3. Configuration management: Update configuration items
  4. Form processing: Update form data
  5. State management: Update state in frameworks like React

Released under the MIT License.