Skip to content

replace

Replace an item in an array

161 bytes

Usage

Given an array of items, replace the one that matches the given condition function. Only replaces the first match. Always returns a copy of the original array.

import * as
import _
_
from 'radashi'
const
const fish: {
name: string;
weight: number;
}[]
fish
= [
{
name: string
name
: 'Marlin',
weight: number
weight
: 105,
},
{
name: string
name
: 'Bass',
weight: number
weight
: 8,
},
{
name: string
name
: 'Trout',
weight: number
weight
: 13,
},
]
const
const salmon: {
name: string;
weight: number;
}
salmon
= {
name: string
name
: 'Salmon',
weight: number
weight
: 22,
}
// read: replace fish with salmon where the name is Bass
const
const replaced: {
name: string;
weight: number;
}[]
replaced
=
import _
_
.
replace<{
name: string;
weight: number;
}>(array: readonly {
name: string;
weight: number;
}[], newItem: {
name: string;
weight: number;
}, match: (item: {
name: string;
weight: number;
}, idx: number) => boolean): {
name: string;
weight: number;
}[]
export replace

Replace an element in an array with a new item without modifying the array and return the new value.

@seehttps://radashi.js.org/reference/array/replace

@example

replace([1, 2, 3], 4, (n) => n === 2)
// [1, 4, 3]

@version12.1.0

replace
(
const fish: {
name: string;
weight: number;
}[]
fish
,
const salmon: {
name: string;
weight: number;
}
salmon
,
f: {
name: string;
weight: number;
}
f
=>
f: {
name: string;
weight: number;
}
f
.
name: string
name
=== 'Bass') // => [marlin, salmon, trout]