DEV Community

Miguel Ramirez
Miguel Ramirez

Posted on

Javascript [array methods] - slice, splice

const items: any[] = [0,1,2,3,4,5]
/* syntax
slice()
slice(start)
slice(start, end)
*/

console.log(`
from3: ${items.slice(3)}
from2To4: ${items.slice(2,4)}
all: ${items.slice()}
`)

/*
splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, โ€ฆ, itemN)
*/

items.splice(4,0,"X")
console.log(`insert in index 4: ${items}`)
items.splice(1,1,"Y")
console.log(`replace in index 1: ${items}`)
items.splice(7,0,"i1","i2", "i3")
console.log(`added at the end: ${items}`)
Enter fullscreen mode Exit fullscreen mode

result:

[LOG]: "
from3: 3,4,5
from2To4: 2,3
all: 0,1,2,3,4,5
"
[LOG]: "insert in index 4: 0,1,2,3,X,4,5"
[LOG]: "replace in index 1: 0,Y,2,3,X,4,5"
[LOG]: "added at the end: 0,Y,2,3,X,4,5,i1,i2,i3"

Top comments (0)