Must Know Array Manipulations
2 min read
You're probably familiar with
shift. They come
in handy for sure, if you want to add and remove elements from the beginning or
the end of the array.
However, there are a TON of different scenarios where you will need to insert and remove array elements from any position.
This is worth memorizing cold!
Let's start with an array of animals...
const animals = ['😺' , '🙉' , '🧞','🦊', '🦁', '🐯', '🐵'];
Wait! There's a genie in the list at index 2. Not sure how that snuck in there 😂. Let's go ahead and remove that array element.
const genieIndex = 2; animals.splice(genieIndex,1); console.log(animals); // => ['😺' , '🙉' ,'🦊', '🦁', '🐯', '🐵'];
splice(index,1) removes the array element located at
index. Very simple.
🐶 is feeling left out, so let's add him into the array at
Again, we can use the splice array method.
const index = 2; animals.splice(index, 0,'🐶'); console.log(animals); // => ['😺' , '🙉' ,'🐶','🦊', '🦁', '🐯', '🐵'];
splice(index, 0,'🐶') inserts the dog emoji at position
Now there are definitely more sophisticated array manipulations you can do with
splice. However, start by memorizing how to add and remove array elements with
splice. You'll thank me later!
Did you find this article valuable?
Support Amit Mehta by becoming a sponsor. Any amount is appreciated!