Array Methods

These are the most commonly used Array methods;

  • Push and Pop – Add/Remove from the end of an array
  • Shift and Unshift – Remove/Add from the start of an array
  • IndexOf – Will find the index of a value within the array
  • Slice – Used to copy parts of an array

Push and Pop

Push will always add to the end of an Arrays index. Meaning don’t have to keep track of the index numbers.
var names = ['Tom','Alex','Tilly'];
names.push('Charlie');

This would output;
["Tom", "Alex", "Tilly", "Charlie"]

To remove the last index within the array you would use something like;
names.pop(); // This would remove Charlie from the end of the array.

Unshift and Shift

Unshift and shift are a bit backwards in the fact that unshift is used to add to the start of the array and shift is used to remove the first item in the array.
var names = ['Tom','Alex','Tilly'];
names.unshift(“Charlie”);

This would output;
[“Charlie”,“Tom”,”Alex”,”Tilly”];

To remove the first index within the array you would use something like;
names.shift(); // This would remove Charlie from the start.

You can also place it within another variable;
var nam = names.shift();

IndexOf

This is used to find the index of a value within an array. If the value isn’t within the array, it will return a -1.

var names = ['Tom','Alex','Tilly'];
names.indexOf(“Alex”) // This would return 1.
names.indexOf(“Elliot”) // This would return -1 as it isn’t within the array.

Slice

This is used to copy parts of an array.

var names = ['Tom','Alex','Tilly'];
var family = names.slice(1,3); // Within the parameters you specify the start(1) and the end(3). The end has to be the one after where you want it to end, so index end of 6 would be 7.

This would output;
["Alex", "Tilly"] //

You can also use the slice() function to copy a whole array.
var names = ['Tom','Alex','Tilly'];
var MoreNames = names.slice();

About This Author

I'm 25 years old, I work as a Software Analyst and in my spare time I enjoy gaming, coding, reading and learning new things! I started this 'blog' as a place to post what I'm interested in and as i learn and develop new skills I can post about them to see how far I've progressed!

Comments are closed