loading...
Cover image for Empting Arrays: .splice() & array.lenght = 0

Empting Arrays: .splice() & array.lenght = 0

giandodev profile image GiandoDev ・1 min read

.splice(index to start,Number of element to delete)

The easiest way to empty an array is by setting its length to 0

const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.length = 0


// return apples = []

We may also use

const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(0)


// return apples = empty array[]

If we want delete the first apple

const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(0,1)


// return apples = [ 'green apple', 'yellow apple', 'Mac' ]

If we want delete the second apple

const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(1,1)


// return apples = [ 'red apple', 'yellow apple', 'Mac' ]

If we want delete the second and third apples

const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(1,2)


// return apples = [ 'red apple', 'Mac' ]

More about .splice() MDN

Posted on May 1 by:

giandodev profile

GiandoDev

@giandodev

Hi, I am Giandomenico. I love to learn new stuff and solve problems.

Discussion

markdown guide
 

what about assigning it to an empty array
apples = [];

 

const apples = ['red apple', 'green apple', 'yellow apple', 'Mac']
apples.splice(0,0, 'Japan apple') // I add a 'Japan apple' in index[0], and I wan't remove anythings.
now apples is [ 'Japan apple', 'red apple', 'green apple', 'yellow apple', 'Mac' ]
I want treate this topic in another article.
have a nice day