JavaScript Arrays
August 01, 2021
| Content |
|---|
| How-to create arrays |
| Frequently used array/ ES6 methods |
| The spread operator and sorting arrays |
Array Initializers
An array is a collection of anything - numbers, strings, objects, functions etc - store into a single variable with zero index.
Two different ways to initialize an array: square brackets or via the new Array constructor.
let nums = [];
let names = new Array();
//Single argument - type number
let exception = new Array(2)
This is a special case, where a single argument passed to the constructor returns an empty array with a length value of 2.
Adding items to an array
Push & Unshift
The push method adds an item or collection of items to the end of an array, while the unshift method adds them to the beginning of an array. Push and unshift mutate the original array.
let fruits = ['melons', 'papayas', 'mangos'];
fruits.push('apple'); //end of array
//beginning of array
fruits.unshift('grapes','watermelon');
//beginning of array
fruits = ['bananas', ...fruits];
//end of array
fruits = [...fruits, 'strawberries'];
Spread operator
The spread operator on the other hand, lets you add an item to the beginning or end of an array.
The spread operator does not mutate the array.
let fruits = ['melons', 'papayas', 'mangos'];
//beginning of array
fruits = ['bananas', ...fruits];
//end of array
fruits = [...fruits, 'strawberries'];
Removing items from an array
The pop method removes the last item from an array, while shift removes the first item. Both mutate the original array.
Slice method of arrays
The slice method removes a segment from an array. It takes 2 parameters: begining and end - end not included. Passing just one parameter into slice, returns everything from that point on in the index. It does not mutate the original array.
let fruits = ['melons', 'papayas', 'mangos'];
var arr1 = fruits.slice(1,2);
console.log(arr1);
$ > (1) ['papayas'] //arr1
$ > (3) ['melons', 'papayas', 'mangos'] //fruits
Since the original array will not change, the outcome should be pass into a new variable, to hold on to it.
Splice method of arrays
The arrays's splice method also removes item(s) from an array, but unlike the slice method it will change the original array. The splice method first parameter is the index number to be removed, and the
second parameter indicates number of items to be removed.
let fruits = ['melons', 'papayas', 'mangos'];
var arr3 = fruits.splice(1);
console.log(arr3)
$ > (2) ['papayas', 'mangos'] //arr3
$ > ['melons] //fruits
Adding up arrays
There's a few different ways for adding up arrays together. The most common way it's probably using the concat method.
Here below there are three separate arrays: grades, fruits and days. I then create a new array newArray, and apply the concat method to grades, in order to add them all up.
let grades = [55,77,99],
fruits = ['apples','grapes'],
days = ['Monday','Saturday','Sunday'];
let newArray = grades.concat(fruits, days);
Should point out that were you to initialize the newArray var prior to add them up, what you'll get is a multidimensional array. The concat method of arrays already returns a new array.
Multi-dimensional arrays
JavaScript does not provide multidimensional arrays natively. But you can do so by creating an array and then placing other arrays inside of it. Below three arrays enclosed by newArr.
let newArr = [ grades, fruits, days ];
>$ (3) [Array(3), Array(2), Array(3)]
This below does not creates a multi-dimensional array, but an array similar to what I got earlier on using the concat method.
let anotherArr = [...grades,...fruits,...days ];//or
anotherArr.push(...grades,...fruits,...days);
Joining elements of an array
The join method returns a new concatenated string of all elements as shown below.
let fruits = ['melons', 'papayas', 'mangos'];
let x = fruits.joins();
$ > "melons,papayas,mangos"
Looping through an array
Several methods exist to iterate over arrays in JavaScript, such as:
for loop, for each, for in, find, map, filter and reduce among the most commonly used.
Array forEach method
The forEach method takes a function as an argument. The function takes two parameters: the first is the array element and the second is the index.
Example: return the following Discovery Investigations crime titles
let crimeDocumentaries = [
{title: "A Deadly Dose"},
{title: "No Happy Ending"},
{title: "Twisted Sisters"},
{title: "Evil-in-Law"}
];
crimeDocumentaries.forEach((crime) => {
console.log('crime.title');
})
Array for..in loop
The for..in method iterates over enumerable properties. Array elements do not need to be objects to use the for..in method.
Example: return the following Discovery Investigations crime titles
let crimeDocumentaries = [
{title: "Final Cut"},
{title: "Gone"},
{title: "Happily Never After"},
{title: "Home Alone"}
];
for (let prop in crimeDocumentaries) {
console.log(crimeDocumentaries[prop].title);
}
Array map method
The map method iterates through all the items of an array with the results of calling a function on
each of the array elements. It does not change the original array.
Example: Given an array of numbers, multiply every number by five.
The second approach arr2 passes a callback function to map, that gets executed for each element of the array with the returned
values added to arr2.
const nums = [1,2,3,4,5];
let arr1 = nums.map(n => n * 5);
//or
function byFive(n) {
return n * 5;
}
let arr2 = nums.map(byFive);
Array filter method
The filter method returns a new array with all the elements that the callback execution returns true for. Those elements for which the callback execution returns false are omitted from the new array.
Example: Given an array of numbers, returned an array of those greater than five.
The second approach arr2 passes a callback function just like with map above, that runs on each of the elements of the array.
const nums = [1,2,3,4,5,6,7,8,9,10];
let arr1 = nums.filter(n => n > 5);
//or
function greaterThanFive(n) {
return n > 5;
}
let arr2 = nums.filter(greaterThanFive);
Array reduce method
The reduce method executes a reducer function on each element of the array resulting in a single output value.
It basically takes two values: the accumulator and the current value; which are then added together every time the reducer function gets called.
Example below adds up all of the numbers in the array returning 15
const array = [1,2,3,4,5];
function reducer(acc,val) {
return acc + val;
}
array.reduce(reducer)
Sorting an objects array
To sort an object's array, we use the array sort method. The sort method takes in a callback function, which itself takes in two parameters (2 elements) to cycle through the object's array.
These two parameter have to return either -1, +1 or zero. When the first argument appears before the second argument, it will return -1. It'll return +1 when the first argument appears after it, and it'll return 0 to indicate no changes.
let people = [
{name: 'Joe', age: 25, city: 'London'},
{name: 'Tony', age: 34, city: 'Rome'},
{name: 'Jody', age: 29, city: 'Barcelona'},
]
The people array here above gets sorted in an ascending order below.
Descending order sorting
Using this same sorting example, I could then invoke/chain the JavaScript's built-in array method reverse to the closing parentheses in people.sort + callback.
people.sort((a,b) => {
if (a.name < b.name) return -1
if (a.name > b.name) return +1;
return 0;
})
people.sort() //when call without passing any arguments, it'll just return the same array.
Sorting posts by their dates
Having just sorted the guides page posts on this site. Here's a very similar data structure to the one I've just used.
const posts = [
{
title: "A few things about arrays",
date: "2021-08-01"
},
{
title: "JS equality",
date: "2021-08-11"
},
{
title: "Web workers",
date: "2021-08-03"
},
{
title: "React hooks",
date: "2021-08-16"
},
{
title: "How [this] happened",
date: "2021-08-04"
}
]
After running the function below over this array, a new array is created/returned with React hooks title on top, followed by JS Equality, Web workers etc.
The sort method of Array takes as parameter 2 objects contained in the array. The main difference
being
that I'm using the new Date() constructor.
To make this function reusable, I've abstracted the array param from the sortedObjects function, updated its name to: sortingByDate to better reflect its functionality, and call it passing an array.
//let sortedObjects = (arr) => {
let sortingByDate = arr => {
return arr.sort((a,b) => {
let ad = new Date(a.date);
let bd = new Date(b.date);
return bd - ad;
})
}
//sort posts in a data collection
let sortedDates = sortingByDate(edges);