JavaScript Arrays in a Nutshell for Newbies
A critical aspect of solving computer science problems is expressing the data in one or more forms (data structures), making it easier to perform some operations on the data. For example, a list of numbers represented as a binary search tree can be efficiently queried to check for the presence of a number and this brings us to the meaning of Data Structure.
What is Data Structure? According to Wikipedia, a data structure is the organization and implementation of values and information. In simple words, data structure is the way of organizing data in an efficient manner.
The thing is, most programming languages make a couple of basic data types available such as strings, numbers, booleans, dictionaries, tuples, sets, etc; from which more complex data structures can be built. For JavaScript, one of such fundamental data types is the ARRAY data type, and it is very important for beginners to understand how they can use arrays.
In this post, we will look at how we can create arrays in JavaScript, and also explore in a nutshell, 12 of the most popular array methods commonly used when working with arrays. This post is meant for JavaScript newbies who desire to know about arrays.
Letβs go! πππ
What is an Array?
An array is simply a data structure that can hold a collection of items (elements). Each element in an array has a position assigned to it, called an index. The indexes usually start from 0
, for the first element. Indexes are properties on an array and can be used to access corresponding elements of the array.
In more specific terms, an array is a list-like object with a length
property and positive integer properties as indexes.
Creating an array
JavaScript arrays can be created in many ways but in this article, we will be focusing on just three ways of creating array:
Array Literal:
The array literal notation wraps the elements of the array (as a comma-separated list of items) in a pair of square brackets ([]
). Any property or method available on the Array
prototype can be accessed on the newly created array object.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
console.log(fruits.length);
// 5
Array Constructor:
A new array object can be created by calling the Array()
constructor with the elements of the array as arguments. The constructor function can be called with or without the new
keyword β the effect is basically the same. Hence, the following is similar to the array literal from before:
const fruits = new Array('banana', 'mango', 'orange', 'apple', 'melon');
console.log(fruits.length);
// 5
Spread Operators: An array can be created from another array using the spread operator. The spread operator is simply used to list the enumerable elements of an iterable object in array and is represented using three dots (β¦)
Note: Spread operator can be used to clone an iterable object or merge iterable objects into one.
const = age [30, 20, 13, 34, 56]
const = combineAge [...age, 3, 7, 10, 24]
console.log(combineAge);
// [30, 20, 13, 34, 56, 3, 7, 10, 24]
Elements of an array
There is no limitation to the kind of elements a JavaScript array can contain. JavaScript arrays are designed to be heterogeneous by nature β they can contain one or more elements of any data type. For example, the array in the code snippet below contains elements of the following types: boolean, string, function, number and object.
const myArray = [true, (a, b) => a + b, 'house', 18, 'jane', {fruit: 'banana'}]
Since an array can contain just any type of element, it means that it's possible for an array to contain arrays β in which case it is commonly referred to as a multidimensional array (array of arrays), as shown below:
// Multidimensional Array
// An array that contains arrays (array of arrays)
const names = [
['John', 'Lola', 'Doe','Judith'],
['Hillary', 'Chidi', 'Humphrey', 'Mariam'],
['Alex', 'Usman', 'Cynthia', 'James']
];
There are times when you want an array to be homogeneous β to contain elements of the same data type. For example, say you want to perform some arithmetic operations on each element of an array; the elements of the array will have to at least be of number
type for this to be successful.
// Array with only strings
const countries = ['kenya', 'nigeria', 'london', 'ghana', 'senegal'];
// Array with only positive integers (numbers)
const scores = [23, 67, 78, 20, 10, 26, 36];
Unfortunately, JavaScript on its own has no way of ensuring that an array is homogeneous at run-time. It is however the responsibility of the developer to do the type checks necessary before using the array as intended.
JavaScript is not strictly typed β it is impossible to specify the types of content you want an array to contain at compile-time just like you could in Java, C++ or other strictly typed languages. If you are using a typed superset of JavaScript such as TypeScript, it is possible to do this at compile time. However, the program might still be prone to failures at run time, especially if it works with data from an external source.
// TYPESCRIPT EXAMPLE: HOMOGENEOUS ARRAYS (AT COMPILE TIME)
// Array with only strings
const countries: string[] = ['kenya', 'nigeria', 'london', 'ghana', 'senegal'];
// Array with only positive integers (numbers)
const scores: Array<number> = [23, 67, 78, 20, 10, 26, 36];
Popular Array Methods
The Array
prototype is enriched with a lot of methods for working with arrays. These methods usually serve as the foundation for implementing even more complex operations on arrays.
map()
This method returns a new array with the results of calling the provided map function on every element of an array.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
const sweetFruits = fruits.map(fruit => 'sweet ' + fruit);
console.log(sweetFruits);
// ["sweet banana", "sweet mango", "sweet orange", "sweet apple", "sweet melon"]
const ages = [23, 30, 13, 18, 40];
const doubleAges = ages.map(age => age * 2);
console.log(doubleAges);
// [46, 60, 26, 36, 80]
forEach()
This method can be used to iterate through the elements of an array, calling the provided callback function for each element. Unlike the map()
method, the value returned by the callback function is usually ignored, and this method does not create a new array. It is commonly used when you want to cause some side-effects based on each element of an array.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
const sweetFruit = [];
fruits.forEach(fruit => {
sweetFruit.push('sweet' + fruit);
});
// ["sweet banana", "sweet mango", "sweet orange", "sweet apple", "sweet melon"]
filter()
This method returns a new array containing only the elements for which the provided filter function returned truthy value. The filter function provides logic for the test condition. Elements that donβt pass the condition specified in the filter function are discarded and not included in the new array that is returned.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
const fruitsWithLongNames = fruits.filter(fruit => {
return fruit.length > 5;
});
// ["banana", "orange"]
join()
This method is used to add the elements of the array together into a single string.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
console.log(fruits.join());
// "banana,mango,orange,apple,melon"
console.log(fruits.join(' - '));
// "banana - mango - orange - apple - melon"
includes()
This method checks whether an array includes an element among its entries, returning true
or false
as appropriate.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
console.log(fruits.includes('mango')); // true
console.log(fruits.includes('pineapple')); // false
reduce()
The reduce method is used in an array, to sum up elements of the array to one value or Item. The summation of the elements starts from the left to the right of the array. The reduce() method is likely to be one of the tricky or difficult array methods to understand.
Note: reduce() is one of the most powerful array methods. In fact, .reduce()
can be used to do what both .map()
and .filter()
can do.
const numbers = [4, 5, 1, 4, 2, 3, 1];
const sumOfNumbers = numbers.reduce((sum, number) => sum + number, 0);
console.log(sumOfNumbers); // 20
indexOf()
This method returns the position (index) at which a given element can be found in the array. It will return -1
if the element is not found in the array.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
console.log(fruits.indexOf('melon')); // 4
console.log(fruits.indexOf('pineapple')); // -1
concat()
This method is used to join two or more arrays. This method does not change the existing arrays but instead returns a new array.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
const foods = ['yam', 'rice', 'beans', 'potato'];
console.log(fruits.concat(foods));
// ["banana", "mango", "orange", "apple", "melon", "yam", "rice", "beans", "potato"]
push()
This method adds one or more elements to the end of an array and returns the new length of the array.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
const fruitsCount = fruits.push('pineapple');
console.log(fruits);
// ["banana", "mango", "orange", "apple", "melon", "pineapple"]
console.log(fruitsCount);
// 6
pop()
This method removes the last element from an array and returns that element. Calling .pop()
decreases the length of the original array.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
console.log(fruits.pop()); // "melon"
console.log(fruits.length); // 4
slice()
This method simply takes a chunk/part of an array and returns it as a new array. When using the slice()
method, two parameters are passed which are the startIndex
β representing the index to start copying from, and the endIndex
β representing the index before which to end the slice.
Note: Calling this method without arguments has been a very useful technique for creating array clones. If called directly from the Array.prototype
, then it could be used to convert array-likes to arrays.
// Example 1
const names = ['James', 'Bola', 'Henry', 'Abiola', 'Musa'];
const newNames = names.slice();
console.log(newNames);
// ["James", "Bola", "Henry", "Abiola", "Musa"]
// Example 2
const names = ['James', 'Bola', 'Henry', 'Abiola', 'Musa'];
const newNames = names.slice(2);
console.log(newNames);
// ["Henry", "Abiola", "Musa"]
// Example 3
const names = ['James', 'Bola', 'Henry', 'Abiola', 'Musa'];
const newNames = names.slice(1, 3);
console.log(newNames);
// ["Bola", "Henry"]
find()
This method returns the value of the first element in the array that satisfies the condition defined in the provided testing function.
const fruits = ['banana', 'mango', 'orange', 'apple', 'melon'];
const foundFruit = fruits.find(fruit => fruit.length >= 5);
console.log(foundFruit); // "banana"
Conclusion
In this post, we were able to learn about working with JavaScript arrays and some of the useful methods they possess. Arrays are one of the most important data types in JavaScript and every developer ought to be familiar with how to use them.
Yaay! I hope you enjoyed the post. π·π·