DEV Community

Abdurrahman Fadhil
Abdurrahman Fadhil

Posted on • Originally published at rahmanfadhil.com

How to CRUD an Array in JavaScript

Read the original article here

There are two ways to create, update, and delete items to an array in JavaScript. The first approach is by using the destructive methods which will change the object itself.

The second approach is by using the immutable methods, which will return a new array that contains a new updated value. This could be very useful if your using Redux or any other state management library.

Let's say we have an array contains a some items like below.

const list = ["Item 1", "Item 2", "Item 3"]
Enter fullscreen mode Exit fullscreen mode

Create item

The mutable way:

const newItem = "Item 4"

list.push(newItem)
Enter fullscreen mode Exit fullscreen mode

The immutable way:

const newItem = "Item 4"

const newList = list.concat([newItem])
Enter fullscreen mode Exit fullscreen mode

Result:

[
  "Item 1",
  "Item 2",
  "Item 3",
  "Item 4"
]
Enter fullscreen mode Exit fullscreen mode

Update item

The mutable way:

const itemIndex = 1
const newItem = "Item 2 (updated)"

list[itemIndex] = newItem
Enter fullscreen mode Exit fullscreen mode

The immutable way:

const itemIndex = 1
const newItem = "Item 2 (updated)"

const newList = list.map((item, index) => {
  return index === itemIndex ? newItem : item
})
Enter fullscreen mode Exit fullscreen mode

Result:

[
  "Item 1",
  "Item 2 (updated)",
  "Item 3"
]
Enter fullscreen mode Exit fullscreen mode

Delete item

The mutable way:

const itemIndex = 1

list.splice(itemIndex, 1)
Enter fullscreen mode Exit fullscreen mode

The immutable way:

const itemIndex = 1

const newList = list.filter((item, index) => {
  return index !== itemIndex
})
Enter fullscreen mode Exit fullscreen mode

Result:

[
  "Item 1",
  "Item 3"
]
Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
monsieurmechant profile image
Adam Mechant

I think there is a typo in your immutable create example.
You've switched the name of the variable of the initial array from list to state

Collapse
 
rahmanfadhil profile image
Abdurrahman Fadhil

Fixed 👌, thanks for pointing out a problem!

Collapse
 
gamorales profile image
Guillermo Alfonso Morales

Nice post 👍

Collapse
 
rahmanfadhil profile image
Abdurrahman Fadhil

Thanks!

Collapse
 
stevepenner profile image
Steve P.

If those are JavaScript statements, they need to end in a semicolon.

Collapse
 
deciduously profile image
Ben Lovy • Edited

Not necessarily - it's definitely useful for code clarity, but in JS many statements are implicitly terminated by a newline. The StandardJS style guide omits them when not explicitly necessary.