DEV Community

Cover image for JavaScipt: Everything you need to know about arrays.
The daily developer
The daily developer

Posted on • Edited on

JavaScipt: Everything you need to know about arrays.

Arrays are superheroes when it comes to organizing data. This article explains how they function, why they're essential for anyone looking to properly manage data and how to effectively manipulate it.

Overview :

  1. What is an array?
  2. Initializing an array
  3. length property
  4. Accessing and changing array elements
  5. Multi-dimensional array
  6. Array Methods

What is an array?

Think of an array as a multi-drawer cabinet. Each drawer in that cabinet has a different item in it. You can reach an item by simply opening the drawer that has the item you want.

Similarly an array is a variable that can store multiple values.

Initializing an array

We've previously seen how to Initialize a variable.

let name = "John";
Enter fullscreen mode Exit fullscreen mode

Array literal

Initializing an array is similar to initializing a variable with some differences. While a variable can store a single data type as we've seen in the example above, an array can hold multiple values of different data types. You declare an array using square brackets.

const food = [];
Enter fullscreen mode Exit fullscreen mode

You can pass multiple values of different data types to the square brackets to initialize the array.

const values = ["ice cream", 57, "biscuit", true, 3.14];
Enter fullscreen mode Exit fullscreen mode

New Keyword

You can also declare and assign values to an array using the new keyword.

const values = new Array();
const elements = new Array("one", 2, true, 3.14);
Enter fullscreen mode Exit fullscreen mode

These two methods do exactly the same thing, but use the array literal method for efficiency, readability, and speed.

Length Property

In the previous article How to make the most out of strings We've seen what the length property does. Let's go over it one more time.
The length property returns the size of the array or the number of items in the array.

const values = ["ice cream", 57, "biscuit", true, 3.14];
console.log(values.length); //5
Enter fullscreen mode Exit fullscreen mode

Accessing and changing array elements

The position of an item in an array is known as an index. We start counting the items of an array from zero. This is known as zero-based indexing.

const values = ["ice cream", 57, "biscuit", true, 3.14];
let index0 = values[0];
console.log(index0); //ice cream
Enter fullscreen mode Exit fullscreen mode

Let's change an item in the values array

const values = ["ice cream", 57, "biscuit", true, 3.14];
values[1] = 26;
console.log(values);
//[ 'ice cream', 26, 'biscuit', true, 3.14 ]
Enter fullscreen mode Exit fullscreen mode

As we can see the number 57 was modified to 26.

The length property always starts counting from 1. It's always 1 number higher than than the index
You can access array elements using the length property. For example, let's access the last item and second to last item of the values array.

const values = ["ice cream", 57, "biscuit", true, 3.14];

console.log(values[values.length-1]); //3.14
console.log(values[values.length-2]); //true
Enter fullscreen mode Exit fullscreen mode

So what's happening in the example? Let's break it down.
We've previously accessed the first element of the array using this notation values[0] which gave us ice cream.
values[values.length-1] here is values[5 - 1] which is value[4] which will give us 3.14.
Why are we using -1?
As we've previously stated arrays use zero-based indexing. if we try to get the value at value[5] we will get undefined which means that there's no value assigned to the index 5 since we start counting from zero. Counting from 0 to 4 gives us five values which is the length of the array.

const values = ["ice cream", 57, "biscuit", true, 3.14];

console.log(values[values.length]); //undeifned
Enter fullscreen mode Exit fullscreen mode

Multi-dimensional array

Now that we have a strong understanding of what an array is, let's explain what a multi-dimensional array is.

A multi-dimensional array is an array that contains other arrays.

const multiDimensional = [
  [2, "cat", false],
  [3.14, true, "mango"],
  ["peach", 32, true]
];
Enter fullscreen mode Exit fullscreen mode

Multi-dimensional arrays can be accessed in the same way as an array by using bracket notation. Take our multiDimensional array which has 1 outer layer which is the entire array.

const multiDimensional = [
  [2, "cat", false],
  [3.14, true, "mango"],
  ["peach", 32, true]
];

console.log(multiDimensional[0]); //[2, "cat", false]
console.log(multiDimensional[1]); //[3.14, true, "mango"]
console.log(multiDimensional[2]); //["peach", 32, true]
Enter fullscreen mode Exit fullscreen mode

The inner layer consists of 3 inner layers which are the 3 arrays. The items (values) within each inner array belong to the inner layer.

Let's say we want to access the value mango in our example:

const multiDimensional = [
  [2, "cat", false],
  [3.14, true, "mango"],
  ["peach", 32, true]
];

console.log(multiDimensional[1][2]);//mango
Enter fullscreen mode Exit fullscreen mode

Our value mango is the second array in multiDimensional, so it's in position 1 (remember zero-based indexing). The mango value is the last item in that array meaning at position 2.

Array methods

Array operations like insertion, deletion, searching, and transformation can be performed on an array's elements using array methods. These methods make writing custom code less difficult and create more readable, compact and useful code.

Method Description
push() Adds one or more elements to the end of an array.
unshift() Adds one or more elements to the beginning of an array.
splice() Adds or removes elements from an array at a specified index.
pop() Removes the last element from the end of an array and returns it.
shift() Removes the first element from the beginning of an array and returns it.
map() Creates a new array by applying a function to each element of the array.
filter() Creates a new array with elements that pass a certain condition.
reverse() Reverses the order of elements in an array.
sort() Sorts the elements of an array in place or based on a provided function.
copyWithin() Copies elements within an array to a specified destination.
indexOf() Returns the first index at which a given element can be found in the array.
lastIndexOf() Returns the last index at which a given element can be found in the array.
includes() Checks if an array includes a certain element, returning a boolean.
find() Returns the first element in the array that satisfies a given condition.
findIndex() Returns the index of the first element that satisfies a given condition.
join() Joins all elements of an array into a string using a specified separator.
toString() Converts an array to a string representation.
concat() Combines two or more arrays, returning a new concatenated array.
Spread Operator (...) Expands an array into individual elements.
slice() Returns a shallow copy of a portion of an array into a new array.
reduce() Applies a function against an accumulator and each element in the array, reducing it to a single value.

Add methods

We can add an element to an array using multiple methods.

  • Using indexing
const values = [2, "cat", false]

values[3] ="miami";
console.log(values); //[2, "cat", false, "miami"]
Enter fullscreen mode Exit fullscreen mode
  • Using length property
const values = [2, "cat", false]

values[values.length] ="miami";
console.log(values); //[2, "cat", false, "miami"]
Enter fullscreen mode Exit fullscreen mode

Using these methods is not recommended because it can create undefined "holes" in an array.

const values = [];
values[2] = 'Hello';

console.log(values);        // Output: [ , , 'Hello' ]
console.log(values.length); // Output: 3
console.log(values[0]);     // Output: undefined
console.log(values[1]);     // Output: undefined
console.log(values[2]);     // Output: 'Hello'
Enter fullscreen mode Exit fullscreen mode
Category Array Methods
Element Insertion push(), unshift(), splice()
  • push()

The push() method alters the array by adding a single or more values to the end of it and returns the new length of the altered array.

const numbers = [1, 2, 3];
const newLength = numbers.push(4, 5);

console.log(numbers);    // Output: [1, 2, 3, 4, 5]
console.log(newLength);  // Output: 5
Enter fullscreen mode Exit fullscreen mode
  • unshift()

The unshift() method is used to add a single or multiple values to the beginning of the array and returns its new length.

const numbers = [3, 4, 5];
const newLength = numbers.unshift(1, 2);

console.log(numbers);    // Output: [1, 2, 3, 4, 5]
console.log(newLength);  // Output: 5
Enter fullscreen mode Exit fullscreen mode
  • splice()

The splice() method is used to add remove or replace values at a specified index.
Here's an example of using splice to add and remove elements:

const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruits = fruits.splice(1, 2, 'melon', 'cherry');

console.log(fruits);          
// Output: ['apple', 'melon', 'cherry', 'grape']
console.log(removedFruits);    
// Output: ['banana', 'orange'] (removed elements)
Enter fullscreen mode Exit fullscreen mode

Remove methods

Category Array Methods
Element Deletion pop(), shift(), splice()
  • delete()
const values = ["apple", true, 2, "Mango"];
delete values[1];
console.log(values); //['apple', <1 empty item>, 2, 'Mango']
console.log(values.length);//4
Enter fullscreen mode Exit fullscreen mode

It is not recommended to remove an item from an array using the delete() method because the original array length remains unchanged because it only removes the value from the array without freeing up that index. Meaning the length of the array stays the same.

  • pop()

The pop() method alters the array by removing the last element from the array and returns the removed value.

const numbers = [1, 2, 3, 4, 5];
const removedElement = numbers.pop();

console.log(numbers);         // Output: [1, 2, 3, 4]
console.log(removedElement);  // Output: 5 (last element)
Enter fullscreen mode Exit fullscreen mode
  • shift()

The shift() method alters the array by removing the first element of it and returns the removed value.

const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruit = fruits.shift();

console.log(fruits);         // Output: ['banana', 'orange', 'grape']
console.log(removedFruit);   // Output: 'apple' (first element)
Enter fullscreen mode Exit fullscreen mode

Transform methods

Category Array Methods
Element Transformation map(), filter(), reverse(), reduce(),sort(), copyWithin()

The map(), filter(), and reduce() methods are higher order functions which we'll discuss in an upcoming article. All you have to know for now is that they're array methods do not modify the original array but return a new modified array.

  • reverse()

The reverse() method alters the original array and reverses the order of its values.

const numbers = [1, 2, 3, 4, 5];
numbers.reverse();

console.log(numbers);  // Output: [5, 4, 3, 2, 1] (original array is reversed)
Enter fullscreen mode Exit fullscreen mode
  • sort()

The sort() method alters the original array and sorts its values in ascending order.

const fruits = ['banana', 'apple', 'grape', 'orange'];
fruits.sort();

console.log(fruits);  // Output: ['apple', 'banana', 'grape', 'orange'] (sorted alphabetically)

//sorting numbers
const numbers = [4, 2, 8, 6, 1];
numbers.sort((a, b) => a - b);

console.log(numbers);  // Output: [1, 2, 4, 6, 8] (sorted numerically)
Enter fullscreen mode Exit fullscreen mode

When sorting numbers in ascending order, the expression a - b is frequently used as a comparison function. This method makes use of the sort() method's behavior, which assumes the comparison function that returns a negative, zero, or positive value to determine the order of elements.
Why a - b ?

  1. If a - b returns a negative value, it indicates that a should come before b in the sorted order.
  2. If a - b returns zero, it indicates that a and b are considered equal in terms of sorting order.
  3. If a - b returns a positive value, it indicates that a should come after b in the sorted order.
  • copyWithin()

The copyWithin() method does not modify the array and copies a piece of it to another place in the array.
it takes 3 parameters:

  • target: which is where the elements you're copying will be placed.
  • start: which is from where this method will start copying the elements in the array.
  • end: Which is the index prior to which copies of elements should stop. It takes the array's length as a default if omitted.
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3, 5);

console.log(numbers);  // Output: [4, 5, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Search methods

Category Array Methods
Element Search indexOf(), lastIndexOf(), includes(), find(), findIndex()
  • indexOf()

The indexOf() method returns the index of the element you're trying to find and -1 if it was not found.

const fruits = ['apple', 'banana', 'orange', 'apple'];
const index = fruits.indexOf('apple');

console.log(index);  // Output: 0 (index of the first 'apple')
Enter fullscreen mode Exit fullscreen mode
  • lastIndexOf()

The lastIndexOf() method returns the index of last occurrence of the element you're trying to find and -1 if it was not found.

const fruits = ['apple', 'banana', 'orange', 'apple'];
const lastIndex = fruits.lastIndexOf('apple');

console.log(lastIndex);  // Output: 3 (index of the last 'apple')
Enter fullscreen mode Exit fullscreen mode
  • includes()

The includes() method indicates if an element is present in an array. It returns true if the element is in the array and false if it is not.

const fruits = ['apple', 'banana', 'orange'];
const hasBanana = fruits.includes('banana');

console.log(hasBanana);  // Output: true (array includes 'banana')
Enter fullscreen mode Exit fullscreen mode

find and findIndex methods are both higher order functions which we will discuss in a later article.

Conversion methods

Category Array Methods
Element Conversion join(), toString()
  • join()

The join() method creates a string using the argument passed as a separator.

const fruits = ['apple', 'banana', 'orange'];
const joinedString = fruits.join(', ');

console.log(joinedString);  // Output: "apple, banana, orange"
Enter fullscreen mode Exit fullscreen mode
  • toString()

The toString() method converts the array into a string separated by comas.

const numbers = [1, 2, 3, 4, 5];
const numbersString = numbers.toString();

console.log(numbersString);  // Output: "1,2,3,4,5"
Enter fullscreen mode Exit fullscreen mode

Copy methods

Category Array Methods
Copying concat(), Spread Operator (...), slice()
  • concat()

The concat() method joins two or more arrays together and returns a new array.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = array1.concat(array2);

console.log(combinedArray);  // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
  • The spread operator (...)

This operator is used to expand element of an array and can be used to combine arrays.

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const combinedArray = [...array1, ...array2];

console.log(combinedArray);  // Output: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
  • slice()

The slice() method is used to create a copy of a portion of an array and returns a new array.

const numbers = [1, 2, 3, 4, 5];
const copiedNumbers = numbers.slice(1, 4);

console.log(copiedNumbers);  // Output: [2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
dannyjrt profile image
Daniel Todd

Thank you for this explanation. I am relatively new to the world of coding, but I have quickly seen the importance of Arrays. The usefulness of storing different types of data into a single variable has been so helpful!

Thank you for the built in methods as well, some of these are going to be so useful going forward.

Best,
Daniel Todd

Collapse
 
fullstackjo profile image
The daily developer

Hey Daniel! i am happy to hear that you've found my explanation clear and useful! If you find yourself having a question feel free to leave it in a comment and i will try my best to provide you with the help you need!

-Jo