Create a new array
There are two ways: with square brackets or using the new
constructor.
const numbers = [1,2,3,4,5];
// or
const numbers = new Array(1,2,3,4,5);
And the same with an array containing strings.
const fruits = ['apples', 'oranges', 'pears', 'stink badgers'];
// or
const fruits = new Array('apples', 'oranges', 'pears', 'stink badgers');
NB. Note the use of the capital letter (Pascal case) when using the new
keyword.
Arrays can take a mixture of value types:
const various = ['apples', true, 12.3, null];
Accessing an item in an array using it’s index, that is it’s position by number starting with 0
.
const fruit = ['bananas', 'strawberries', 'pears'];
console.log(fruit[1]);
Array methods
There are three broad categories of array methods:
- Mutator methods change the array in some way
- Accessor methods return a new value or representation
- Iteration methods operate on each item in the array one at a time (like loops)
However there are many in each category. However it’s worth noting that some are extremely useful and you’ll need to know well whilst others you may never use at all.
Full list of array methods
concat()
AcccopyWithIn()
Mutentries()
Itevery()
Itfill()
Mutfilter()
Itfind()
ItfindIndex()
ItforEach()
ItArray.from()
includes()
ItindexOf()
isArray()
join()
lastIndexOf()
map()
push()
pop()
shift()
unshift()
reduce()
reverse()
toReversed()
slice()
some()
sort()
toSorted()
splice()
toSpliced()
toString()
values()
See full list with descriptions at Tutorials Tonight
const fruit = ['bananas', 'strawberries', 'pears'];
fruit[3] = 'grapes';
Note this is not reassigning the variable, just manipulating it which is why this works with const
.
Some methods for arrays. The first adds an item to the end of the array
fruit.push('grapes'); // adds to the end
fruit.unshift('grapes'); // adds to the beginning
fruit.pop(); // removes the last item
fruit.isArray(); // checks if it is an array - boolean
fruit.indexOf('grapes') // gets the position in the array.
Get the last item
let lastFruitIndex = fruit.length - 1; // subtract 1 because index counting begins with 0
fruit[lastFruitIndex]
Note the default separation of a single comma.
Looping through arrays
Whilst you can loop through arrays using the traditional Javascript for
loop there are a number of array methods that make this job simpler with specifc funcionality.
These iterator methods are:
forEach()
map()
filter()
some()
- checks whether at least one of the elements of the array satisfies the condition checked by the argument function.
You can loop through an array using the forEach()
method which is more concise than regular for
loop and is specifically for looping through arrays.
Given an array:
const myArray = ['fish', 'bananas', 'old pyjamas', 'mutton', 'beef', 'trout' ];
You can print this list to the console using forEach()
myArray.forEach((item, index, arr) => {
console.log(item, index, arr)
})
oooh.