Everything You Need To Know About ARRAYS
Tags: javascript, webdev, programming, array
Published: 2022-07-23 15:17:29

## INTRODUCTION
The array is the most common data structure in computer programming. Every programming language includes some form of array. Arrays are commonly used in computer programs to **organize data** so that a **related set of values** can be easily sorted or searched.

So for most of my code snippet I will be using the JavaScript language which I am most comfortable with but, I'll also make sure to write the code so that other programmers from other languages can understand.
## DEFINITION OF AN ARRAY
An array is a **data structure** that contains a group of elements. Typically, these elements are all the same data type, such as an integer or string.

For example, imagine that a score table in a game needs to record ten scores. One way to do this is to have a variable for each score:

```
score_0
score_1
score_2
score_3
score_4
score_5
score_6
score_7
score_8
score_9
```

This would work, but there is a better way. It is much simpler to keep all the related data under one name. We do this by using an array.
Instead of having ten variables, each holding a score, there could be one array that holds all the related data:
score(9)

Well, you might be wondering why score(9)? When we have 10 scores, that is because arrays are zero-indexed; that is - when elements are stored in an array, an index/key is assigned to each element of the array to enable us to access or mutate this element in the future.

Here's an illustration:


![array.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1657850800573/sqr0d0Ggc.png align="left")

It helps to think of an array as a row of cells, like the ones found in a table. Each cell represents an element. The individual values, or array elements, are numbered 0 to 9 because arrays start counting at 0.

In another example, a search engine may use an array to store Web pages found in a search performed by the user. When displaying the results, the program will output one element of the array at a time. This may be done for a specified number of values or until all the values stored in the array have been output. While the program could create a new variable for each result found, storing the results in an array is a much more efficient way to manage memory.

The syntax for storing and displaying the values in an array typically looks something like this:


```
arrayname[0] = "This ";
arrayname[1] = "is ";
arrayname[2] = "pretty simple.";
``` 

```
console.log(arrayname[0]);
console.log(arrayname[1]);
console.log(arrayname[2]);
``` 

The above commands would print the first three values of the array, or **"This is pretty simple."**

By using a **"while"** or **"for"** loop, the programmer can tell the program to output each value in the array until the last value has been reached. So not only do arrays help manage memory more efficiently, they make the programmer's job more efficient as well.

## USING ARRAYS
There are several ways to create arrays, access array elements, and perform tasks such as searching and sorting the elements stored in an array. In this section, we'll discuss several array methods and properties.

### Creating an Array
The simplest way to create an array is by declaring an array variable using the [] operator:
```
var numbers = [];
```
When you create an array in this manner, you have an array with length of 0. You can verify this by calling the built-in length property:
```
console.log(numbers.length); // displays 0
```
Another way to create an array is to declare an array variable with a set of elements inside the [] operator:
```
var numbers = [1,2,3,4,5];
console.log(numbers.length); // displays 5
```
You can also create an array by calling the **Array constructor**:
```
var numbers = new Array();
console.log(numbers.length); // displays 0
```
You can call the Array constructor with a set of elements as arguments to the constructor:
```
var numbers = new Array(1,2,3,4,5);
console.log(numbers.length); // displays 5
```
Finally, you can create an array by calling the Array constructor with a single argument specifying the length of the array:
```
var numbers = new Array(10);
console.log(numbers.length); // displays 10
```
Unlike many other programming languages, but common for most scripting languages,
JavaScript array elements do not all have to be of the same type:

```
var objects = [1, "Joe", true, null];
``` 
We can verify that an object is an array by calling the Array.isArray() function, like
this:
```
var numbers = 3;
var arr = [7,4,1776];
console.log(Array.isArray(number)); // displays false
console.log(Array.isArray(arr)); // displays true
```
We’ve covered several techniques for creating arrays. As for which function is best, most JavaScript's experts recommend using the [] operator, saying it is more efficient than calling the Array constructor.

### Accessing and Writing Array Elements
Data is assigned to array elements using the [] operator in an assignment statement.
For example, the following loop assigns the values 1 through 100 to an array:
```
var nums = [];
for (var i = 0; i < 100; ++i) {
  nums[i] = i + 1;
}
```
Array elements are also accessed using the [] operator. For example:
```
var numbers = [1,2,3,4,5];
var sum = numbers[0] + numbers[1] + numbers[2] + numbers[3] +
numbers[4];
console.log(sum); // displays 15
```
Of course, accessing all the elements of an array **sequentially** is much easier using a for
loop:
```
var numbers = [1, 2, 3, 5, 8, 13, 21];
var sum = 0;
for (var i = 0; i < numbers.length; ++i) {
  sum += numbers[i];
}
console.log(sum); // displays 53
```
Notice that the for loop is controlled using the length property rather than an integer literal. Because JavaScript arrays are objects, they can grow beyond the size specified when they were created. By using the length property, which returns the number of elements currently in the array, you can guarantee that your loop processes all array elements.

### Creating Arrays from Strings 
#### (Split method)
Arrays can be created as the result of calling the split() function on a string. This
function breaks up a string at a common delimiter, such as a space for each word, and
creates an array consisting of the individual parts of the string.

The following short program demonstrates how the split() function works on a simple
string:

```
var sentence = "the quick brown fox jumped over the lazy dog";
var words = sentence.split(" ");
for (var i = 0; i < words.length; ++i) {
  console.log("word " + i + ": " + words[i]);
}
``` 
The output from this program is:

```
word 0: the
word 1: quick
word 2: brown
word 3: fox
word 4: jumped
word 5: over
word 6: the
word 7: lazy
word 8: dog
``` 
#### (Array.from() method)
The Array.from() function is an inbuilt function in JavaScript which creates a new array instance from a given array. In case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, the new array instance simple take the elements of the given array.
```
var sentence = "the quick brown fox jumped over the lazy dog";
var words = Array.from(sentence);
console.log(words)
``` 

```
[
  't', 'h', 'e', ' ', 'q', 'u', 'i',
  'c', 'k', ' ', 'b', 'r', 'o', 'w',
  'n', ' ', 'f', 'o', 'x', ' ', 'j',
  'u', 'm', 'p', 'e', 'd', ' ', 'o',
  'v', 'e', 'r', ' ', 't', 'h', 'e',
  ' ', 'l', 'a', 'z', 'y', ' ', 'd',
  'o', 'g'
]
``` 
### Aggregate Array Operations
There are several aggregate operations you can perform on arrays. First, you can assign one array to another array:
```
var nums = [];
for (var i = 0; i < 10; ++i) {
  nums[i] = i+1;
}
var samenums = nums;
```
However, when you assign one array to another array, you are assigning a reference to the assigned array. When you make a change to the original array, that change is reflected in the other array as well. The following code fragment demonstrates how this works:
```
var nums = [];
for (var i = 0; i < 100; ++i) {
  nums[i] = i+1;
}
var samenums = nums;
nums[0] = 400;
console.log(samenums[0]); // displays 400
```
This is called a shallow copy. The new array simply points to the original array’s elements. A better alternative is to make a deep copy, so that each of the original array’s elements is actually copied to the new array’s elements. An effective way to do this is to create a function to perform the task:
```
function copy(arr1, arr2) {
  for (var i = 0; i < arr1.length; ++i) {
    arr2[i] = arr1[i];
  }
}
```
Now, the following code fragment produces the expected result:

```
var nums = [];
for (var i = 0; i < 100; ++i) {
  nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
console.log(samenums[0]); // displays 1
``` 
## Accessor Functions
JavaScript provides a set of functions you can use to access the elements of an array. These functions, called accessor functions, return some representation of the target array as their return values.
### Searching for a Value
One of the most commonly used accessor functions is **indexOf()**, which looks to see if the argument passed to the function is found in the array. If the argument is contained in the array, the function returns the index position of the argument. If the argument is not found in the array, the function returns -1. Here is an example:
```
var names = ["David", "Cynthia", "Raymond", "Clayton", "Jennifer"];
putstr("Enter a name to search for: ");
var name = readline();
var position = names.indexOf(name);
if (position >= 0) {
  console.log("Found " + name + " at position " + position);
}
else {
  console.log(name + " not found in array.");
}
```
If you run this program and enter Cynthia, the program will output:
```
Found Cynthia at position 1
```
If you enter Joe, the output is:
```
Joe not found in array.
```
If you have multiple occurrences of the same data in an array, the indexOf() function will always return the position of the first occurrence. A similar function, **lastIndexOf()**, will return the position of the last occurrence of the argument in the array, or -1
if the argument isn’t found.

Here is an example:
```
var names = ["David", "Mike", "Cynthia", "Raymond", "Clayton", "Mike", "Jennifer"];
var name = "Mike";
var firstPos = names.indexOf(name);
console.log("First found " + name + " at position " + firstPos);
var lastPos = names.lastIndexOf(name);
console.log("Last found " + name + " at position " + lastPos);
```
The output from this program is:
```
First found Mike at position 1
Last found Mike at position 5
```
### String Representations of Arrays
There are two functions that return string representations of an array: **join()** and **toString()**. Both functions return a string containing the elements of the array delimited by commas.

Here are some examples:
```
var names = ["David", "Cynthia", "Raymond", "Clayton", "Mike", "Jennifer"];
var namestr = names.join();
console.log(namestr); // David,Cynthia,Raymond,Clayton,Mike,Jennifer
namestr = names.toString();
console.log(namestr); // David,Cynthia,Raymond,Clayton,Mike,Jennifer
```

### Creating New Arrays from Existing Arrays
There are two accessor functions that allow you create new arrays from existing arrays: **concat()** and **splice()**. 

The concat() function allows you to put together two or more arrays to create a new array, and the splice() function allows you to create a new array from a subset of an existing array.
Let’s look first at how concat() works. The function is called from an existing array, and its argument is another existing array. The argument is concatenated to the end of the array calling concat(). The following program demonstrates how concat() works:
```
var cisDept = ["Mike", "Clayton", "Terrill", "Danny", "Jennifer"];
var dmpDept = ["Raymond", "Cynthia", "Bryan"];
var itDiv = cis.concat(dmp);
console.log(itDiv);
itDiv = dmp.concat(cisDept);
console.log(itDiv);
```
The program outputs:
```
Mike,Clayton,Terrill,Danny,Jennifer,Raymond,Cynthia,Bryan
Raymond,Cynthia,Bryan,Mike,Clayton,Terrill,Danny,Jennifer
```
The first output line shows the data from the cis array first, and the second output line shows the data from the dmp array first.

The splice() function creates a new array from the contents of an existing array. The arguments to the function are the starting position for taking the splice and the number of elements to take from the existing array. 

Here is how the method works:
```
var itDiv = ["Mike","Clayton","Terrill","Raymond","Cynthia","Danny","Jennifer"];
var dmpDept = itDiv.splice(3,3);
var cisDept = itDiv;
console.log(dmpDept); // Raymond,Cynthia,Danny
console.log(cisDept); // Mike,Clayton,Terrill,Jennifer
```
There are other uses for splice() as well, such as modifying an array by adding and/or removing elements. See the [Mozilla Developer Network website](http://mzl.la/1gmmlQ5) for more information.

## Mutator Functions
JavaScript has a set of mutator functions that allow you to modify the contents of an array without referencing the individual elements. These functions often make hard techniques easy, as you’ll see below.
### Adding Elements to an Array
There are two mutator functions for adding elements to an array: **push()** and **unshift()**. The push() function adds an element to the end of an array:
```
var nums = [1,2,3,4,5];
console.log(nums); // 1,2,3,4,5
nums.push(6);
console.log(nums); // 1,2,3,4,5,6
```
Using push() is more intuitive than using the length property to extend an array:
```
var nums = [1,2,3,4,5];
console.log(nums); // 1,2,3,4,5
nums[nums.length] = 6;
console.log(nums); // 1,2,3,4,5,6
```
Adding data to the beginning of an array is much harder than adding data to the end of an array. To do so without the benefit of a mutator function, each existing element of the array has to be shifted up one position before the new data is added. Here is some code to illustrate this scenario:
```
var nums = [2,3,4,5];
var newnum = 1;
var N = nums.length;
for (var i = N; i >= 0; --i) {
  nums[i] = nums[i-1];
}
nums[0] = newnum;
console.log(nums); // 1,2,3,4,5
```
This code becomes more inefficient as the number of elements stored in the array increases. The mutator function for adding array elements to the beginning of an array is unshift(). Here is how the function works:
```
var nums = [2,3,4,5];
console.log(nums); // 2,3,4,5
var newnum = 1;
nums.unshift(newnum);
console.log(nums); // 1,2,3,4,5
nums = [3,4,5];
nums.unshift(1,2);
console.log(nums); // 1,2,3,4,5
```
The second call to unshift() demonstrates that you can add multiple elements to an array with one call to the function.
### Removing Elements from an Array
Removing an element from the end of an array is easy using the **pop()** mutator function:
```
var nums = [1,2,3,4,5,9];
nums.pop();
console.log(nums); // 1,2,3,4,5
```
Without mutator functions, removing elements from the beginning of an array requires shifting elements toward the beginning of the array, causing the same inefficiency we see when adding elements to the beginning of an array:
```
var nums = [9,1,2,3,4,5];
console.log(nums);
for (var i = 0; i < nums.length; ++i) {
  nums[i] = nums[i+1];
}
console.log(nums); // 1,2,3,4,5,
```
Besides the fact that we have to shift the elements down to collapse the array, we are also left with an extra element. We know this because of the extra comma we see when we display the array contents.

The mutator function we need to remove an element from the beginning of an array is **shift()**. Here is how the function works:
```
var nums = [9,1,2,3,4,5];
nums.shift();
console.log(nums); // 1,2,3,4,5
```
You’ll notice there are no extra elements left at the end of the array. Both pop() and shift() return the values they remove, so you can collect the values in a variable:
```
var nums = [6,1,2,3,4,5];
var first = nums.shift(); // first gets the value 9
nums.push(first);
console.log(nums); // 1,2,3,4,5,6
```
### Adding and Removing Elements from the Middle of an Array
Trying to add or remove elements at the end of an array leads to the same problems we find when trying to add or remove elements from the beginning of an array—both operations require shifting array elements either toward the beginning or toward the end of the array. However, there is one mutator function we can use to perform both operations—**splice()**.

To add elements to an array using splice(), you have to provide the following arguments:

• The **starting index** (where you want to begin adding elements)

• The **number of elements to remove** (0 when you are adding elements)

• The **elements you want to add** to the array

Let’s look at a simple example. The following program adds elements to the middle of an array:
```
var nums = [1,2,3,7,8,9];
var newElements = [4,5,6];
nums.splice(3,0,newElements);
console.log(nums); // 1,2,3,4,5,6,7,8,9
```
The elements spliced into an array can be any list of items passed to the function, not necessarily a named array of items. 

For example:
```
var nums = [1,2,3,7,8,9];
nums.splice(3,0,4,5,6);
console.log(nums);
```
In the preceding example, the arguments 4, 5, and 6 represent the list of elements we want to insert into nums.
Here is an example of using splice() to remove elements from an array:

```
var nums = [1,2,3,100,200,300,400,4,5];
nums.splice(3,4);
console.log(nums); // 1,2,3,4,5
``` 
### Putting Array Elements in Order
The last two mutator functions are used to arrange array elements into some type of order. The first of these, **reverse()**, reverses the order of the elements of an array.

Here is an example of its use:
```
var nums = [1,2,3,4,5];
nums.reverse();
console.log(nums); // 5,4,3,2,1
```
We often need to sort the elements of an array into order. The mutator function for this task, **sort()**, works very well with strings:
```
var names = ["David","Mike","Cynthia","Clayton","Bryan","Raymond"];
nums.sort();
console.log(nums); // Bryan,Clayton,Cynthia,David,Mike,Raymond
```
But sort() does not work so well with numbers:
```
var nums = [3,1,2,100,4,200];
nums.sort();
console.log(nums); // 1,100,2,200,3,4
```
The sort() function sorts data lexicographically, assuming the data elements are strings, even though in the preceding example, the elements are numbers. We can make the sort() function work correctly for numbers by passing in an ordering function as the first argument to the function, which sort() will then use to sort the array elements. This is the function that sort() will use when comparing pairs of array elements to determine their correct order.

For numbers, the ordering function can simply subtract one number from another number. If the number returned is negative, the left operand is less than the right operand; if the number returned is zero, the left operand is equal to the right operand; and if the number returned is positive, the left operand is greater than the right operand. 

With this in mind, let’s rerun the previous small program using an ordering function:
```
function compare(num1, num2) {
  return num1 - num2;
}
var nums = [3,1,2,100,4,200];
nums.sort(compare);
console.log(nums); // 1,2,3,4,100,200
```
The sort() function uses the compare() function to sort the array elements numerically rather than lexicographically.

## Iterator Functions
The final set of array functions we examine areiterator functions. These functions apply a function to each element of an array, either returning a value, a set of values, or a new array after applying the function to each element of an array.
### Non–Array-Generating Iterator Functions
The first group of iterator functions we’ll discuss do not generate a new array; instead, they either perform an operation on each element of an array or generate a single value from an array. The first of these functions is **forEach()**. This function takes a function as an argument and applies the called function to each element of an array.

Here is an example of how it works:
```
function square(num) {
  console.log(num, num * num);
}
var nums = [1,2,3,4,5,6,7,8,9,10];
nums.forEach(square);
```
The output from this program is:
```
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
10 100
```
The next iterator function,** every()**, applies a Boolean function to an array and returns true if the function can return true for every element in the array.

Here is an example:
```
function isEven(num) {
  return num % 2 == 0;
}
var nums = [2,4,6,8,10];
var even = nums.every(isEven);
if (even) {
  console.log("all numbers are even");
}
else {
  console.log("not all numbers are even");
}
```
The program displays:
```
all numbers are even
```
If we change the array to:
```
var nums = [2,4,6,7,8,10];
```
the program displays:
```
not all numbers are even
```
The **some()** function will take a Boolean function and return true if at least one of the elements in the array meets the criterion of the Boolean function.

For example:
```
function isEven(num) {
  return num % 2 == 0;
}
var nums = [1,2,3,4,5,6,7,8,9,10];
var someEven = nums.some(isEven);
if (someEven) {
  console.log("some numbers are even");
}
else {
  console.log("no numbers are even");
}
nums = [1,3,5,7,9];
someEven = nums.some(isEven);
if (someEven) {
  console.log("some numbers are even");
}
else {
  console.log("no numbers are even");
}
```
The output from this program is:
```
some numbers are even
no numbers are even
```
The **reduce()** function applies a function to an accumulator and the successive elements of an array until the end of the array is reached, yielding a single value. Here is an example of using reduce() to compute the sum of the elements of an array:
```
function add(runningTotal, currentValue) {
  return runningTotal + currentValue;
}
var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add);
console.log(sum); // displays 55
```
The reduce() function, in conjunction with theadd() function, works from left to right,
computing a running sum of the array elements, like this:
```
add(1,2) -> 3
add(3,3) -> 6
add(6,4) -> 10
add(10,5) -> 15
add(15,6) -> 21
add(21,7) -> 28
add(28,8) -> 36
add(36,9) -> 45
add(45,10) -> 55
```
We can also use reduce() with strings to perform concatenation:
```
function concat(accumulatedString, item) {
  return accumulatedString + item;
}
var words = ["the ", "quick ","brown ", "fox "];
var sentence = words.reduce(concat);
console.log(sentence); // displays "the quick brown fox"
```
JavaScript also provides a **reduceRight()** function, which works similarly to reduce(), only working from the righthand side of the array to the left, instead of from left to right. The following program uses reduceRight() to reverse the elements of an array:
```
function concat(accumulatedString, item) {
  return accumulatedString + item;
}
var words = ["the ", "quick ","brown ", "fox "];
var sentence = words.reduceRight(concat);
console.log(sentence); // displays "fox brown quick the"
```
### Iterator Functions That Return a New Array
There are two iterator functions that return new arrays: **map()** and **filter()**. 

The map() function works like the forEach() function, applying a function to each element of an array. The difference between the two functions is that map() returns a new array with the results of the function application. 

Here is an example:
```
function curve(grade) {
  return grade += 5;
}
var grades = [77, 65, 81, 92, 83];
var newgrades = grades.map(curve);
console.log(newgrades); // 82, 70, 86, 97, 88
```
Here is an example using strings:
```
function first(word) {
  return word[0];
}
var words = ["for","your","information"];
var acronym = words.map(first);
console.log(acronym.join("")); // displays "fyi"
```
For this last example, the acronym array stores the first letter of each word in the words array. 

However, if we want to display the elements of the array as a true acronym, we need to get rid of the commas that will be displayed if we just display the array elements using the implied toString() function. We accomplish this by calling thejoin() function with the empty string as the separator.

The filter() function works similarly to every(), but instead of returning true if all the elements of an array satisfy a Boolean function, the function returns a new array consisting of those elements that satisfy the Boolean function. 

Here is an example:
```
function isEven(num) {
  return num % 2 == 0;
}
function isOdd(num) {
  return num % 2 != 0;
}
var nums = [];
  for (var i = 0; i < 20; ++i) {
  nums[i] = i+1;
}
var evens = nums.filter(isEven);
console.log("Even numbers: ");
console.log(evens);
var odds = nums.filter(isOdd);
console.log("Odd numbers: ");
console.log(odds);
```
This program returns the following output:
```
Even numbers:
2,4,6,8,10,12,14,16,18,20
Odd numbers:
1,3,5,7,9,11,13,15,17,19
```
Here is another interesting use of filter():
```
function passing(num) {
  return num >= 60;
}
var grades = [];
for (var i = 0; i < 20; ++i) {
  grades[i] = Math.floor(Math.random() * 101);
}
var passGrades = grades.filter(passing);
console.log("All grades: );
console.log(grades);
console.log("Passing grades: ");
console.log(passGrades);
```
This program displays:
```
All grades:
39,43,89,19,46,54,48,5,13,31,27,95,62,64,35,75,79,88,73,74
Passing grades:
89,95,62,64,75,79,88,73,74
```
Of course, we can also use filter() with strings. Here is an example that applies the spelling rule “i before e except after c”:
```
function afterc(str) {
if (str.indexOf("cie") > -1) {
  return true;
}
  return false;
}
var words = ["recieve","deceive","percieve","deceit","concieve"];
var misspelled = words.filter(afterc);
console.log(misspelled); // displays recieve,percieve,concieve
```

At this point, i think i've been able to explain what arrays are how we use them and how to use the several inbuilt functions in Javascript to perform some Array operations.

In a later part of this article we shall be looking into Two-dimensional and Multi-dimensional forms of arrays, Arrays of objects and Arrays in objects.

See you next time.