DEV Community

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

Posted on

2

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

.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

Top comments (2)

Collapse
 
arung86 profile image
Arun Kumar G

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

Collapse
 
giandodev profile image
GiandoDev

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay