JavaScript: Update Array Immutably dengan `with()`
1
min read .
Updated on
Kalau kamu ingin mengubah elemen array tanpa mengubah array asli, with()
jawabannya.
1. Dasar with()
let newArray = array.with(index, value);
- Membuat array baru dengan elemen di
index
digantivalue
. - Array asli tetap utuh.
Contoh:
const colors = ['red','blue','green','yellow'];
const updatedColors = colors.with(1,'purple');
console.log(updatedColors); // ['red','purple','green','yellow']
console.log(colors); // ['red','blue','green','yellow']
2. Gunakan untuk Immutable Updates
const items = ['item1','item2','item3'];
const updatedItems = items.with(2,'newItem');
console.log(updatedItems); // ['item1','item2','newItem']
console.log(items); // ['item1','item2','item3']
3. Kombinasi dengan Metode Lain
const numbers = [1,2,3,4,5];
const modifiedNumbers = numbers.with(3,100).map(num => num*2);
console.log(modifiedNumbers); // [2,4,6,200,10]
console.log(numbers); // [1,2,3,4,5]
4. Kegunaan Real-World
- UI Updates: Update elemen di daftar/tabel tanpa mengubah data asli.
- State Management: Cocok untuk Redux atau sistem yang memerlukan immutability.
- Data Processing: Non-destructive updates untuk dataset penting.
5. Catatan Performa
Membuat array baru → butuh memory tambahan, jadi perhatikan jika array besar.
Kesimpulan
with()
memungkinkan update elemen array secara immutable, bikin kode lebih aman, predictable, dan selaras dengan prinsip functional programming.