Codementor Events

Introduction to Javascript arrays

Published Jun 18, 2021
Introduction to Javascript arrays

An array is a data structure we may use in our program to describe list-like data. For example, if we have homogeneous data items that can be grouped, we may use arrays.

What the data structure is? It's how we organize, format and store what we need in our program. It allows us to have an efficient access to it.

Creating an array

Javascript array

Arrays may store any other Javascript data types such as strings, numbers, booleans, other arrays, objects, functions. In the image above, we declare the constant array and tell the program to create an array by writing [] - the literal notation.

We may instantiate an array via other approaches.

We used the Array constructor, which creates an array with a length of 2. Length? Every array has the length property that tells us how many items this array stores. So, arrays have properties, like objects? Correct. Even more, arrays are objects!

Though arrays don't look like {}, they are optimized internally in a way to assist programmers to manage list-like data more efficiently, than doing so in objects.

[1, 2] we may write as {"1": 1, "2": 2} but thus we miss the efficiency in managing data arrays can provide.

What the constructor is? It's a global class that allows us to create something. In the case above, we used Array constructor, which also is a global object with useful methods.

Using the Array constructor we can create an array with not undefined items: new Array(1, 2) will create [1, 2].

What the undefined is? It's a Javascript primitive type such as strings, numbers and booleans. undefined is a property of the global object. It's a value that tells us a variable is not defined. Read more.

Adding items to an array

Let's take a look at real-world example! How do we store our list of hobbies?

Each hobby is a string. Okay. What if we want to add more hobbies? We might create a completely new array with amended hobbies list. It's an option, but how to add items to an existing array?

Add items to array via push

The push method does we wanted! But why hobbies has push method? As hobbies is an array, it inherits methods and properties from its parent - the Array global object. For instance, the length property we use to see how many items an array has.

The push method modifies the existing array by adding an item to the end of it. Pay attention to that, because some array methods return a new transformed array, they don't modify it. We'll take a look at those methods later.

Reading array items

Let's read the items in hobbies:

const hobbies = ["reading", "walking"];
hobbies.push("coding");

console.log(hobbies); // ["reading", "walking", "coding"]
// Read a specific element
// Usage: array[index] where index(a number of an element) starts from 0
console.log(hobbies[0]); // read the first element, output: "reading"
console.log(hobbies[1]); // returns the 2nd element: ["walking"]

What if we want to read the last element? Remember length property? It tells us how many items an array has.

// hobies: ["reading", "walking", "coding"]
// hobbies.length is 3
const lastHobbyIndex = hobbies.length - 1; // 2
const lastHobby = hobbies[lastHobbyIndex]; // "coding"

But why just not hobbies[hobbies.length]? As you may remember, indexes start from 0, but length shows an amount of items. If we have an array with one item, then length would 1, but the index to read the element is 0. So the shortcut to read the last element is hobbies[hobbies.length - 1].

What about adding an element not to the end, but to the start?

const hobbies = ["reading"];
hobbies.unshift("coding");
console.log(hobbies); // ["coding", "reading"]

Removing array items

const hobbies = ["coding", "reading"];

// Remove from the beginning
hobbies.shift(); // hobbies now is: ["reading"]

// Let's add one more item
hobbies.push("talking"); // hobbies now is: ["reading", "talking"]

// Remove from the end
hobbies.pop(); // hobbies now is: ["reading"]

Notice: operations such as adding and removing an item to the beginning of an array are slower. Why? Imagine you have an array:

const arr = [1, 2, 3, 4, 5];
arr.pop();
// Was: [1, 2, 3, 4, 5]
// Became: [1, 2, 3, 4, <will be deleted>]
// * "will be deleted" isn't shown

arr.shift();
// Was: [1, 2, 3, 4]
// Became: [<will be deleted>, 2, 3, 4]
// So in order to have [2, 3, 4] we should move the remaining items
// to the left. Thus, their positions change. It requires more
// than 1 operation

Boring? Take a look at this task. Imagine you have a list of words. You need to collect only those that start with "A".

const words = ["Alaska", "cat", "human", "Apple", "Josh", "Array"];

So we should read each item in the array. Meet Array.forEach, a method that consumes 1 argument - a callback function that does something with a current array element.

If you're not familiar yet with Javascript functions, take a look at this article.

words.forEach((currentWord) => {
  // do something with the word
});

Now we can read each word, but what we should do with them? The algorithm is next:

  • Determine whether a word starts with "A" letter.
  • If a word start with "A", add it to a new array of words we need.
  • If a word doesn't start with "A", don't do anything.
// Here we'll be adding the words we look for
const wordsStartingWithA = [];

words.forEach((currentWord) => {
  const doesWordStartWithA = currentWord[0] === "A";
    if (doesWordStartWithA) {
    	wordsStartingWithA.push(currentWord);
    }
});

Wait, currentWord is a string, can we handle it as an array by reading the first element? Yes! currentWord[0] === "A" statement returns a boolean, because we use the strict equality to compare values.

Can you write a program to do the same except finding words that end with "A"? Remember that strings also have length property.

Hint const doesWordEndWithA = currentWord[currentWord.length - 1] === "A";

There is another approach to such a task. Meet the filter method.

const wordsStartingWithA = words.filter((currentWord) => {
  const doesWordStartWithA = currentWord[0] === "A";
    if (doesWordStartWithA) {
    	return true;
    }
    
    return false;
});

It works like forEach with the difference that you should return true of false in the callback function. By returning true you tell you want to keep the current array element. By returning false you skip the element.

Another example:

const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers.filter((number) => number % 2 === 0); // [2, 4, 6]

filter returns a new array. The remainder(%) operator returns the remainder left over when one operand is divided by a second operand.

Tasks to practice

Try to code the following tasks, it'll help you in understanding the topic.

  1. You have an array of numbers. Make a new array that has only odd numbers. Use filter method.
  2. You have an array: ["a", "bb", "ccc", "dddd", "fffff", "abcdefe", "abc", "abbddccff", "x"]. Make a new array from it that contains strings, which length is greater than 4.
  3. You have an array: [1, 60, "string", {}, true, "55", 20, false, () => {}]. Make a new array from it that contains only strings. The typeof operator may help you.
  4. You have an array of arrays, e.g. [[], [1, 2], ["s", true, 5]]. Calculate a sum of length of each array. In this case, it is 5.

Originally posted on metacognitive.me

Discover and read more posts from Serhii C.
get started
post comments2Replies
Morgan Wilde
3 years ago

Awesome post Sergiy! Love your style and pace at which you reveal more and more complex usage.

Serhii C.
3 years ago

Thanks! Glad you liked it!