Arrays in Javascript (With Examples)
Tags: productivity, programming, javascript, tutorial
Published: 2022-09-12 13:30:07

An _array_ in JavaScript can be looked at as a kind of special variable, which is able to hold more than one value at a time. Arrays can contain any data type, including numbers, strings, Booleans and objects.

More specifically, an array is a type of a high-level, list-like object, which consists of an ordered collection (or list) containing zero or more data types. We use numbered indices starting from 0 to access specific items.

Let’s cover the basics with some examples!

## Creating an Array
```js
var shapes = [‘Square’, ‘Circle’, 'Triangle']; 
console.log(shapes.length); // 3
```
How can we access each array item?
```js
var first = shapes[0]; // Square 
var second = shapes[1]; // Circle
var last = shapes[shapes.length — 1]; // Triangle
```

## Looping Over an Array
You could use any looping method, but let's go with `forEach`:
```js
shapes.forEach(function(item, index, array){
  console.log(item, index);
});

// Square 0
// Circle 1
// Triangle 2
```

## Adding to the End of an Array
We use the `push()` method:
```js
var addItem = shapes.push(‘Rectangle’); 

// [“Square”, “Circle”, “Triangle”, "Rectangle"]
```

## Removing from the End of an Array
We use the `pop()` method:
```js
var removeItemEnd = shapes.pop();

// [“Square”, “Circle”, “Triangle"]
```

## Removing from the Front of an Array
We use the `shift()` method:
```js
var removeItemFront = shapes.shift(); 

// [“Circle”, "Triangle"];
```

## Adding to the Front of an Array
We use the `unshift()` method:
```js
var addItemFront = shapes.unshift(‘Hexagon’);

// [“Hexagon”, “Circle”, "Triangle"];
```

## Getting the Index of an Array Item
We use the `indexOf()` method:
```js
var pos = shapes.indexOf(‘Circle’); 

// 1
```

## Removing an Item by Index Position
We use the `splice()` method:
```js
var removedItem = shapes.splice(1, 1); 

// [“Hexagon”, “Triangle”]
```

## Remove Multiple Items From an Index Position
```js
var colors = [‘Red’, ‘Green’, ‘Blue’, ‘Yellow’]; 

console.log(colors); 

// [“Red”, “Green”, “Blue”, “Yellow”] 

var pos = 1, n = 2; 
var removedItems = colors.splice(pos, n); 

// We use n to define the number of items to be removed, from pos until n inclusive.

console.log(colors); 
// [“Red”, “Yellow”] 

console.log(removedItems); 
// [“Green”, “Blue”]
```

## Copying an Array
We assign our array to a new variable using the `slice()` method:
```js
var arrayCopy = shapes.slice(); 

// [“Hexagon”, “Triangle”]
```

## Checking if an Object is an Array
We use the `isArray()` method to test if objects are arrays:
```js
Array.isArray(shapes);

// true
```

## Reversing the Order of an Array
We use the `reverse()` method:
```js
var food = ['pizza', 'pasta', 'salad', 'bread'];

food.reverse();

// ["bread", "salad", "pasta", "pizza"]
```

## Replacing Array Elements with Static Values
We use the `fill()` method to replace elements with a static value:
```js
food.fill("yum");

// ["yum", "yum", "yum", "yum"]
```
If instead, we wished to replace only some elements, we can set start and end points:
```js
food.fill("yum", 1);

// ["bread", "yum", "yum", "yum"]

food.fill("yuck", 2,4);

// ["pizza", "pasta", "yuck", "yuck"]
```

## Sorting an Array
We use the `sort()` method to sort our elements based on the first character in the element.

_Note_: If our first character is identical, it will compare the second, then the third and so on.
```js
var food = ['pizza', 'pasta', 'salad', 'bread'];

food.sort();

// ["bread", "pasta", "pizza", "salad"]
```
If any of our Array items begin with an uppercase character, they would be sorted before lowercase items, such as:
```js
var food = ['pizza', 'pasta', 'Salad', 'bread'];

food.sort();

// ["Salad", "bread", "pasta", "pizza"]
```
When working with arrays of numbers, the default behavior is not what you might expect:
```js
var numbers = [111, 2, 45, 32, 788, 4, 7];

// [111, 2, 32, 4, 45, 7, 788]
```
The `sort()` method only checks the first character in the number.

So for proper ordering, you could create a function like so:
```js
function sortNumber(a,b) {
  return a - b;
}

numbers.sort(sortNumber);

// [2, 4, 7, 32, 45, 111, 788]
```
Or you could go for extra fancy points by using arrow functions:
```js
numbers.sort((a, b) => a - b); // For ascending sort
numbers.sort((a, b) => b - a); // For descending sort
```

## Merging Arrays
We use the `concat()` method to merge two or more arrays together:
```js
var dogs = ['Labrador', 'Chihuahua', 'Greyhound', 'Beagle'];

var cats = ['Persian', 'Siamese', 'Ragdoll', 'Bengal'];

var animals = dogs.concat(cats);

animals;

// ["Labrador", "Chihuahua", "Greyhound", "Beagle", "Persian", "Siamese", "Ragdoll", "Bengal"]
```

## Converting Array Elements into a String
We use the `join()` method:
```js
var dogs = ['Labrador', 'Chihuahua', 'Greyhound', 'Beagle'];

var joinedDogs = dogs.join();

joinedDogs;

// "Labrador,Chihuahua,Greyhound,Beagle"
```
If we want whitespace in our new string or any other separator for that matter, we add it as a parameter to our `join()`, like so:
```js
var joinedDogs = dogs.join(', ');

joinedDogs;

// "Labrador, Chihuahua, Greyhound, Beagle"
```

## map(), filter() and reduce()
We use the `map()` method to apply a function to every element of an array.

Say we want to add 10 to every number in an array:
```js
var numbers = [1, 2, 3, 4, 5];

var add10 = numbers.map((val, i, arr) => {
  return val + 10;
});

numbers;

// [1, 2, 3, 4, 5];

add10;

// [11, 12, 13, 14, 15]
```
We use the `filter()` method to create a new array with the elements that satisfy a condition set by an argument function.

Say we want to filter out negative numbers from an array:
```js
var numbers = [-52, 520, 0, -100, 34];

function isPositive(value) {
  return value > 0;
}

var filtered = numbers.filter(isPositive);

filtered;

// [520, 34]
```
We use the `reduce()` method to reduce an array to a single value.

Say we want to produce the average of all numbers in an array:
```js
var numbers = [300, 43, 888, 2];

var average = numbers.reduce((total, amount, index, array) => {
  total += amount;
  if( index === array.length - 1) { 
    return total / array.length;
  }else { 
    return total;
  }
});

average;

// 308.25
```

## Find the First Element that Satisfies a Function
We use the `find()` method:
```js
var numbers = [10, 20, 30, 40, 50];

var found = numbers.find(function(element) {
  return element > 30;
});

found;

// 40 
```
Similarly, we can use the `findIndex()` method to return the first index position, rather than the element itself:
```js
var numbers = [10, 20, 30, 40, 50];

var found = numbers.findIndex(function(element) {
  return element > 30;
});

found;

// 3
```

## Summary
And there you have it! We’ve reviewed many of the major array methods in JavaScript. We covered how to create and loop an array, how to add and remove elements, how to manipulate arrays and how to apply functions to array elements!

## Conclusion
If you liked this blog post, follow me on [Twitter](https://twitter.com/RembertDesigns) where I post daily about Tech related things!
![Buy Me A Coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijinng8k7bf23v0o6gkj.png) If you enjoyed this article & would like to leave a tip — click [here](https://www.buymeacoffee.com/rembertdesigns)

### 🌎 Let's Connect

- [Portfolio](https://www.rembertdesigns.co/)

- [Twitter](https://twitter.com/RembertDesigns)

- [LinkedIn](https://www.linkedin.com/in/rrembert/)

- [Hashnode](https://rembertdesigns.hashnode.dev/)

- [Devto](https://dev.to/rembertdesigns)

- [Medium](https://medium.com/@rembertdesigns)

- [Github](https://github.com/rembertdesigns)

- [Codepen](https://codepen.io/rembertdesigns)