DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Arrays?
Zoe Mendez
Zoe Mendez

Posted on

Arrays?

In the beginning of your journey learning Javascript, arrays can be quite confusing. There are SO MANY different methods that can be used on them. I know I had trouble when I first started learning. So, let's start in the beginning.

What is an array?

An array is a data structure that holds, well data. It can be strings or other data structures.

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'
]

Enter fullscreen mode Exit fullscreen mode

This is an example of a simple array. This is an array of strings.

const myFruit = [
'apples',['oranges',['bananas'], 'pineapple'],'strawberries'
]

Enter fullscreen mode Exit fullscreen mode

While this one still uses strings you can see that there are arrays embedded in myFruit.

const favoriteFruits = [
{name: 'Joe',
favoriteFruit: 'apples'},
{name: 'Susan',
favoriteFruit: 'bananas'},
{name: 'Steve',
favoriteFruit: 'pineapple'},
{name: 'Betty',
favoriteFruit: 'kiwi'}
]
Enter fullscreen mode Exit fullscreen mode

Here we have an array with nested objects. In my time of learning javascript, this has been the most common form of an array that I have seen.

This sums up what an array is. It can be simple like a few strings or it can have a nested data structure. Next I will talk about different ways to modify the arrays.

Destructive vs. Nondestructive

Before we get into modifying arrays, we need to talk about destructive vs. nondestructive.

Destructive

Destructive refers to idea that you are modifying the original array. There are a few methods that I talk about that are going to be referred to as a destructive method.

Nondestructive

Well, if you assume that nondestructive is the opposite of destructive, then you're CORRECT!! When you use a nondestructive method then you are creating a new array from the original. It's like you have a bag of m&m's and run them threw a machine to pick out the blue and yellow ones to make a new bag. These are the usual preferred methods to use on arrays.

Array Methods

Welcome to the world of modifying arrays! Let's start with the destructive methods.

Destructive

Here's a list of the destructive methods:

  • .push()
  • .unshift()
  • .pop()
  • .shift()
  • .splice()

.push() and .unshift() both add elements to the original array, while .pop() and .shift() both remove elements from the original array.

.push()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.push('pineapple');
myFruit // =>['apples', 'oranges', 'bananas', 'strawberries', 'pineapple']

Enter fullscreen mode Exit fullscreen mode

Here you can see that we used .push() to 'push' pineapple into the original array. .push() will add the passed in element to the end of the array. Which keeps it the same array, but adds a new element into the original.

.unshift()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.unshift('kiwi');
myFruit // =>['kiwi','apples', 'oranges', 'bananas', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

Going back to my original array myFruit, you can see I used .unshift() to add in kiwi. .unshift() will add the new element to the beginning of the original array. Which destructively changes the original array.

.pop()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.pop();
myFruit //=> ['apples', 'oranges', 'bananas']
Enter fullscreen mode Exit fullscreen mode

Back to my original array, .pop() removes the last element of the array. So you can see we no longer have strawberries in the original array. Notice that I don't pass in argument. This is because you can't select what element you are trying to remove. .pop() only removes the last element of the array.

.shift()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.shift();
myFruit //=> ['oranges', 'bananas', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

Once again you can see that there is no argument that is being passed through .shift(), but it did remove apples. .shift() removes the first element of your original array.

.splice()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.splice(2, 1, 'pineapple');
myFruit; // => ['apples', 'oranges', 'pineapple', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

.splice() has a few different ways you can use it. In the example above I used the .splice() operator to remove bananas from my string and insert pineapple in its place. Well, how does it know thats what I wanted? Let's break down the arguments I passed through. The first argument is 2, so that means that the operator starts at that point. That selected bananas. Next, we have 1 which means that it's going to remove one element. Think of it as you've highlighted the starting point and now you're going to delete it and replace it with something new. Next is pineapple, which is the new element thats added into the place of the element you removed. .splice() allows you to more specifically alter the original array. You can choose to add a new element anywhere in the array. You don't have to delete any elements in order to pass in a new element. What does that look like? Let's take the prior example and see.

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.splice(2, 0, 'pineapple');
myFruit; // => ['apples', 'oranges', 'pineapple', 'bananas', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

You can see by passing in a 0 at the second argument, it doesn't remove any of the element it just simply adds the third argument into the array. So now you've seen how you can use .splice() more than 1 way.

Nondestructive

Here is a list of nondestructive methods:

  • .slice()
  • Spread Operator

.slice()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.slice(0,2);
// => ['apples', 'oranges', 'bananas']
myFruit;
//=> ['apples', 'oranges', 'bananas', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

.slice() is a great way to select a certain part of your original array and make it into a new array. Above you can see that the first argument that I passed in was the starting point for the new array. The second argument is the last element I wanted to be grabbed from the original array, so the new array was made up of ['apples', 'oranges', 'bananas'].

Spread Operator

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
const copyMyFruit = ['pineapple', ...myFruit];
copyMyFruit;
// => ['pineapple', 'apples', 'oranges', 'bananas', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

The spread operator allows you to create a new array and add a new element to that array. Above you can see that I added pineapple to a copy of the original array because pineapple was in front of the array it added it to the beginning, but you can also add the element to end by switching the two. You can also add multiple elements when using the spread operator.

Array Iterators

What are array iterators?

Here is a list of the more common used array iterators:

  • .forEach()
  • .map()
  • .filter()
  • .find()
  • .reduce()
  • .some()
  • .every()

Array iterators are different operators that are used on arrays. They each have their own purpose. Some create new arrays, some just help reach different parts of arrays. These are all nondestructive methods to use on arrays.

.forEach()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.forEach(function(myFruit){
console.log(`Can I have some ${myFruit}, please?`)}
//Can I have some apples, please?
//Can I have some oranges, please?
//Can I have some bananas, please?
//Can I have some strawberries, please?
Enter fullscreen mode Exit fullscreen mode

.forEach() loops through the array and will plug in each element to what it's being passed through. Above you can see that I console.log() a string and interpolated the array into it, which gave us the strings that used only one element from the original array.

.map()

const myNumbers =[ 45, 15, 12, 11];
myNumbers.map(function(num){
return num * 5 });
// [225, 75, 60, 55]
Enter fullscreen mode Exit fullscreen mode

.map() returns a new array after the original array is run through the callback function. Above you can see that the function is multiplying each element of the array by five and returning the new array.

.filter()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries'];
myFruit.filter(function (fruit){
    return fruit[3] === 'a'});
//['bananas', 'strawberries']
Enter fullscreen mode Exit fullscreen mode

.filter() returns a new array that past the test of the function that the original array is being run through. The example above shows the test of checking for what fruits third character is a. You can see that only 'bananas', 'strawberries' past the test and are generator into a new array.

.find()

const myNumbers =[ 45, 15, 12, 11];
myNumbers.find(function (num) {
    return num < 13 });
// 12
Enter fullscreen mode Exit fullscreen mode

.find() allows you to pass the array into a function that has a set parameter for what element you are looking for. Above you can see that the parameter I gave was looking for an element that was less than 13. It ran each element through and returned the first element that met that parameter.

.reduce()

const myNumbers =[ 45, 15, 12, 11];
myNumbers.reduce((previousValue, currentValue) => previousValue + currentValue, 10)
//93
Enter fullscreen mode Exit fullscreen mode

.reduce() reduces the array down to one sum. Above I passed in the previous value and starting at 0 there is no number prior, so I set 10 as the base number. Which then the function continues to add each element to the overall total giving us the output of 93.

.some()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries']
myFruit.some(fruit => fruit.length > 4);
//true
Enter fullscreen mode Exit fullscreen mode

.some() returns true or false based off the individual elements in the array. You can see above that we are testing in the elements length is greater than four. Because apples length is greater than 4 it returns true.

.every()

const myFruit = [
'apples', 'oranges', 'bananas', 'strawberries']
myFruit.every(fruit => fruit.length > 6);
//false
Enter fullscreen mode Exit fullscreen mode

.every() returns true or false if the whole array passes the test thats its being passed through. Above you can see that we passed the array in checking if each elements length was longer than six characters. Because apples does not past the test it returns a negative.

This is a brief overview of array methods. If you interested in reading more check out the docs here Array MDN.

Oldest comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.