JAVASCRIPT ARRAYS
Published: 2024-06-02 16:00:45

## WHAT IS AN ARRAY
An array is a collection of data stored in a single variable. Arrays are used to store list of data. They are usually presented in square brackets [], and values are separated by commas. Values in an array are not data type specific. Arrays can accept numbers, string, functions, object, Booleans etc. you can also store multiple data types in the same array.

## Characteristics of an array
•	In JavaScript, arrays are counted from zero. The first item in a JavaScript array is indexed at zero, while the second item is one. When accessing values in the array, the first value will be written as array[0]. So if you have ten items in an array, JavaScript will tell you that the last item of the array has the index of nine. Every element in the array can be accessed by their index number.
•	JavaScript arrays are resizable: you can dynamically increase or reduce the size of a JavaScript array. We will soon discuss how to do this when we get to array methods.
•	JavaScript arrays can contain elements of different data types: it is okay in JavaScript for an array to hold values of with a mix of data types. To prevent this behavior, you may use typed arrays instead. Typed arrays are arrays specifically for numeric data. 
•	JavaScript arrays have properties that can give us information about the arrays, and methods that can be used to manipulate and operate on them.

## Creating Array
There are two ways of creating arrays in javascript. One way is to use the array literal; the second way is using the new keyword.
**1.	Using array literal:**
Syntax

```
        const cities = ['Abuja', 'Cairo', 'London', 'Paris']

        const multipleDataTypeArray = [1990, 'person', { name: "mike", age: 23 }, [1, 2, 3]]

```
You can also create an empty array
`        const emptyArray = [];`
**2.	using the new keyword**
Syntax
`        const cities = new Array('Abuja', 'Cairo', 'London', 'Paris');
`

The array literal is most commonly used, and will be used throughout this course.

## Accessing data from an array

To access the array itself, refer to it by name
`        const cities = new Array('Abuja', 'Cairo', 'London', 'Paris');
        console.log(cities)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ome1o659f8djp73envy4.png)
Data can be accessed in the array by accessing the index number of the data in the array. In the above example, we can see that Abuja has index of 0, Cairo index of 1 and so on. If we intend to access London;
`        console.log(cities[2])`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cpv0utx7uwameose127i.png)
If I decide to change London to Manchester
`        cities[2] = "Manchester";`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1n249pgp274et95t2ib6.png)
We can decide to add a fifth city to the array by adding 1 to the last index or using the number of the array length. 
**Example**
`        cities[4] = 'New York'
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aqiqvyngtv4jxdxv6l0k.png)
Sometimes though, knowing and manipulating the last index of an array may not be easy manually as we just did. However with array properties and array methods, we can easily get relevant information about the array and perform necessary operations.

## Array properties
 Array properties are attribute of arrays that provides relevant information about the array. Some examples of array properties include;
**1.	array.length**
As we may have noticed in previous illustrations, the length property is used to get the number of elements in the array. The length property is read-only; you cannot manually set the figure. 
**Example**
`        const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
        console.log(cities.length)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6zl5i3135q9y2kf8856.png)
However, it is updated automatically whenever an element is added or removed from the array.
`cities[4] = ['Accra']
        console.log(cities.length)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d571ta61qzx2al75b4oq.png)
The length property also counts empty values.
`cities[10] = ['Mumbai']
        console.log(cities)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kkhaossympurktgkymh0.png)
As can be seen from the illustration, the cities array now has eleven elements including 5 empty spaces.

**Array.constructor**
This array property returns the array function.  It is a read only property that is inherited from the prototype chain.
  ` const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
        console.log(cities.constructor);`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/204jn7omaidnef32o5n4.png)
The constructor property can be used for creating new array, checking the type of an object, debugging and testing, creating a copy of an array etc.

**Array.Prototype**
The Prototype property contains methods and properties that are inherited by all the arrays.
To access the Prototype property of an array, use
Array.__proto__
With our cities array;
` const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
        console.log(cities.Prototype);
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n791tttkhik1f7rfigbo.png)

 **isArray property**
The typeof() operator which is normally used for finding data type does not exactly help in identifying an array. This is so because in the actual sense, an array is an object. Therefore if we want to know specifically if the data type of a specific data is an array, we make use of the Array.isArray() property.
So back to our cities example
`        console.log(Array.isArray(cities));`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ln8tq50iyx0ixb8jmjxk.png)

## Array methods
Array methods are functions that can be used to manipulate and transform arrays. These methods are defined on the array prototype, and are available to all arrays.
**push()**
The push() method is used to add element(s) to the end of the array. So instead of counting the number of items in the array and using the index to add items as we have been doing, we let the built-in push() method handles that.
`
        const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
        cities.push('Accra')
	console.log(cities)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qkk8fv5dkkhrblain5uj.png)
**pop()**
When you call the pop method on array, it will remove the last item of the array. To remove Accra from the array;
`cities.pop()`
The pop() method will return Accra and remove it from the cities array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lyhzbm5egqg71mgys2jd.png)
**shift()**
 The shift() method is used to remove items from the beginning of the array. So unlike pop that takes out the last item, shift returns and takes out the first item.
Example
`
        const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
      
        cities.shift()
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16yfcl9aowg372qfbwqi.png)
**unshift()**
The unshift() method is used to add items to the beginning of the array. So items added with the unshift() method will add items from index of zero. 
Example
       
 `cities.shift('Mumbai')`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8tm5cmtpxv8i7xxzce6c.png)
**slice()**
The slice method is used to copy an array, or to cut items from an array into another variable. The slice method takes in two arguments. The first one is where to start slicing from, and the second one is where to stop.
You can create a new array with the slice method, by assigning the sliced items to a new array. This way the original array remains the same.
	

```
 const cities = ['Abuja', 'Cairo', 'London', 'Paris'];      
	 const AfricanCities = cities.slice(0,2);
```
	       

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/458meciuknm30bbd3t3d.png)
**splice()**
 splice() method is used to add, remove and replace items in the array. To add items with the splice method, the function takes in a couple of arguments.
The first argument is for start index of the operation you intend to perform, second argument is for how many items you want to delete, and the subsequent arguments are for the items you intend to add.
Syntax
Array.splice(start index, number of elements to delete, item1 to add, item2 to add, …)
Example for adding items.
` 	  
const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
        cities.splice(2,0, 'Mumbai', 'Accra')
`
From the above code snippet, 2 here which is the first argument signify that we want to insert Mumbai and Accra in a position starting from the index of 2. The second argument 0 is to say that no item should be deleted. And the last two arguments are the names of cities to be added to the cities array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e38thw2v98qsa09m0irl.png)

Replacing items with splice();
` const cities = ['Abuja', 'Cairo', 'Mumbai', 'Accra', 'London', 'Paris']
    cities.splice(2,1, 'Copenhagen')
`
By the arguments of the snippet above, we intend to replace Mumbai with Copenhagen. Hence, we counted the index of Mumbai which is 2, then we indicated that only 1 item should be deleted and specified what we wanted the deleted item to be replaced with in the third argument.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r3bwe79n88nfd19p4sdz.png)

Deleting items with splice;
`const cities = ['Abuja', 'Cairo',  'Accra', 'Copenhagen', 'London', 'Paris']   
    cities.splice(0,3)
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrp2jf92klcym18fn7fn.png)

Since we had no intention of adding new items, we inserted only two arguments. For start point, and number of items to be deleted.
Creating a new array 
 You can use the splice method to create a new array from an existing array using the index number of the items. This is possible because the splice() method returns deleted items. By assigning the output of the splice method to a new variable, you can create a new array.
Example
`const cities = ['Abuja', 'Cairo',  'Accra', 'Copenhagen', 'London', 'Paris']
    const AfricanCities = cities.slice(0,3);
  
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j1lmo2bz99sjgm8ng49g.png)
**sort():**
 The sort method is used to rearrange items in an array in ascending order.
Example
`
const cities = ['Abuja', 'Cairo',  'Accra', 'Mumbai', 'London', 'Paris']
cities.sort()
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mm949a51wrg9sj3x57bk.png)
Example 2
`const numbers = [1, 67,9, 5,98]
numbers.sort()
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4q041rvwacm7fzk7i7a0.png)
If you observe the second example above, the sort method only sorted based on the first figure of the numbers. This is why 67 came before 9. This happened because 6 is less than 9. To avoid this mix-up, you will have to use the compare function along with the sort method. The compare function compares all the values in the array, two values at a time (a, b).
Example
`
const numbers = [1, 67,9, 5,98]
numbers.sort(function(a, b){return a - b});
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3l0er5dckthlul3v0uu0.png)
`reverse():`
The reverse() method reorders the items in an array from behind. The first item in the array becomes the last, while the last becomes the first.
Example
`const cities = ['Abuja', 'Cairo',  'Accra', 'Mumbai', 'London', 'Paris']
cities.reverse()
`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s7x10y6cr6mppk7ndpr.png)

 `   const numbers = [1, 67,9, 5,98]
    numbers.reverse()`


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7rvpt0b638z0ysm0pab.png)
**indexOf():**
This method is used to get the index number of an item in the array.
`	 cities.indexOf('London')`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lomyv9wikk5e67gao268.png)
If the item searched for is not in the array, the index of -1 is returned
**find()**
The find() method is used to get the first element that meets a given criteria. The criteria are usually passed in as a function.
Illustration
`let found = scores.find(score=> score >= 60);`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xr21rwo5kx3ql3xnwlbx.png)
In the above illustration, we passed in an arrow function into the find method to check for the first element in the array that scored 60 and above.
**concat()**
The concat() method is used for merging two or more arrays. The method can be used to create a new array. The values in the original array remain unchanged.

```
const persons = ['Tobi', 'Godia'];
const animals = ['cat', 'dog'];
const places = ['Lagos', 'Florida'];
const things = ['pen', 'pencil']
 
let noun = persons.concat(animals, places, things);

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0yg8h4at5sqvr3ta9lou.png)
You can also concatenate other data types with an arrays using the concat()

```
const materials = ['cement', 'wood'];
const workers = 'engineers';
const tools = {'engineers': 'mixers', 'carpenters': 'hammers'}
const building = materials.concat(workers, tools, 23, true)

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v9u60vvuked6384qk5v5.png)
**toString()**
The toString() method as implied by the name is used to convert arrays to strings

```
const cities = ['Abuja', 'Cairo', 'London', 'Paris'];          
const citiesToString = cities.toString();    
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3vlocl5t57mt02q4xlwk.png)

**join()**
The array join() method is used to convert arrays to strings. The difference between this and toString() is that it gives an optional parameter that allows you to input your desired separator. In case the separator was not indicated, comma is used by default.

```
const cities = ['Abuja', 'Cairo', 'London', 'Paris'];          
const citiesToString = cities.join(' / ');         

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbo2fot05e4doiqzfsm1.png)
**includes()**
The includes() method is used to search if an item is in an array. The method usually outputs a Boolean (true / false). This method searches for strict equality (===).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kj8er4g2glrj8a7eipei.png)

## Summary

In conclusion, arrays are very essential in programming. They are useful in collecting, storing, manipulating, outputting and visualizing data.  The array properties give information about array, whereas the array methods are used to manipulate and modify the array.