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 onitem
(T): The new element to replace withmatcher
(function): Function to match elementsitem
(T): Current elementindex
(number): Index of the current elementarray
(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
- Keep original array unchanged:
replace
does not modify the original array, but returns a new array - Only replace first match: If there are multiple matching elements, only the first one is replaced
- No match found: If no matching element is found, returns the original array
- Performance: Time complexity is O(n), where n is the array length
- Matcher function: The matcher function should return a boolean value
Differences from Other Methods
map()
: Processes all elements, not just the first matching onefilter()
: Only filters elements, cannot replacereplace()
: Specifically designed for replacement operationssplice()
: Modifies the original array, whilereplace
returns a new arrayreplaceOrAppend()
: Appends if no match is found, whilereplace
only replaces
Practical Application Scenarios
- User management: Update user information
- Product management: Update product prices or information
- Configuration management: Update configuration items
- Form processing: Update form data
- State management: Update state in frameworks like React