support@90-10.dev

JavaScript Arrays

Arrays are containers that store multiple values in a single variable, in a 0-indexed ordered list. They can hold any type of data, including numbers, strings, objects, and even other arrays, and are dynamic - i.e. you can add or remove items from an array as needed.

Creating an Array

Literal Syntax

Here is an array that stores 3 elements of different types:

const myArray = ['a', 42, 3.14];

Array Constructor

const myArray = new Array('a', 42, 3.14);

Introspection

Arrays are implemented in JavaScript as objects:

console.log(typeof myArray);  // prints: object

You can check if a variable is an array:

const myArray = ['a', 42, 3.14];
console.log(Array.isArray(myArray)); //prints true

Element indexes

Arrays are 0-indexed, so to access the 3rd element of the array we'll use:

myArray[2];  // returns: 42

Indexes are also used if one wants to extract a range of elements from the array - in the example below we're extracting elements from index 2 to index 4. Notice that index 4 is not included in the response:

myArray.slice(2, 4);   // returns: Array [ 42, 3.14 ]

Iteration

There are several way to iterate though the elements of an array.

Using `forEach`:

myArray.forEach(function(item) {
    console.log(item);
});

The classic `for` loop:

for(let i = 0; i < myArray.length; i++) { 
    console.log(myArray[i]);
}

`for ... in` loop:

for(const item of myArray) {
    console.log(item);
};

Modifying Arrays

push and pop

2 methods are available to add and remove elements from the end of an array: push & pop.

push allows us to add one or more elements at the end of the array - in the example below we're adding a string and an object:

myArray.push('Hello', {'x': 1});
// returns: 5  
// the new number of elements in our array

console.log(myArray);  // prints Array(5) [ "a", 42, 3.14, "Hello", {…} ]

pop removes and returns the last element:

myArray.pop();  // returns: Object { x: 1 }
console.log(myArray);  // prints: Array(4) [ "a", 42, 3.14, "Hello" ]

shift and unshift

To add and remove elements from the beginning of the array, we'll use unshift and shift.

Just like `push`, `unshift` takes one or more parameters:

myArray.unshift('Start', {'y': 2});  // returns:  6
console.log(myArray); 
// prints: Array(6) [ "Start", {…}, "a", 42, 3.14, "Hello" ]

In a similar fashion, `shift` removes and returns the first element:

myArray.shift();   // returns "Start"
console.log(myArray); 
// prints: Array(5) [ {…}, "a", 42, 3.14, "Hello" ]

Filter

Just as the name implies, we are 'filtering' the elements of an array based on a given criteria; in the example below, we're finding all even numbers in an array:

let myArray = [1, 4, 42, 11, 79];
let letters = myArray.filter((item) => {
  return (item % 2) === 0;
});
console.log(letters);  // prints: [4, 42]

Let's look at a slightly more complicated example, retrieving all string elements from an array:

let myArray = ["a", 42, 3.14];
let letters = myArray.filter((item) => {
  return Object.prototype.toString.call(item) === "[object String]";
});
console.log(letters);  // prints: ["a"]

Map

The map method allows us to transform each element of an array into another entity based on a certain flow. Here, we're calling an arrow function on each item of the array:

let myArray = [1, 4, 42, 11, 79];
let doubleArray = myArray.map((item) => {
  return item * 2;
});
console.log(doubleArray);  // prints: [2, 8, 84, 22, 158]

Notice that we're returning a new array whilst the original one remains unchanged.

One very common use case is to return an array containing an object property:

let articles = [
  { title: 'article 1', abstract: 'abstract 1'},
  { title: 'article 2', abstract: 'abstract 2'},
  { title: 'article 3', abstract: 'abstract 3'}
];

let titles = articles.map((article) => {
  return article.title;
})
console.log(titles);  // prints: ["article 1", "article 2", "article 3"]

Reduce

The reduce method might look a bit confusing at first but the clue it's in the name - it reduces the entire array to one value. Let's see how to calculate the sum of all elements in an array:

let myArray = [1, 4, 42, 11, 79];
let total = myArray.reduce((item, currentTotal) => {
  return currentTotal + item;
}, 0);
console.log(total);  // prints: 137

Notice that reduce takes 2 parameters: an arrow function that computes the current step, and the initial value. The value returned at one step is being injected as currentTotal for the next step or returned when we exhausted the array.

We mentioned above that reduce "reduces" the array to one value - that's true when the array is single-dimensional. But it can also be used to flatten multi-dimensional arrays:

let myArray = [[1, 4], 23, [42, 11], 79];
const flatArray = myArray.reduce((currentFlatArray, amount) => {
  return currentFlatArray.concat(amount);
}, []);
console.log(flatArray);  // prints: [1, 4, 23, 42, 11, 79]

Practical Example

Let's compute the words frequency in a piece of text:

let text = 'Alice was beginning to get very tired of sitting ' +
'by her sister on the bank, and of having nothing to do : ' +
'once or twice she had peeped into the book her sister was ' +
'reading, but it had no pictures or conversations in it ... ';


// 1. Split text into words

let words = text.split(" ");


// 2. Compute word count

var wordsCount = words.reduce( (tally, word) => {
  let lowercaseWord = word.toLowerCase();
  tally[lowercaseWord] = (tally[lowercaseWord] || 0) + 1 ;
  return tally;
} , {});


// 3. Sort word count with the most used first

// 3.1. Create array from dictionary

var wordsCountArray = Object.keys(wordsCount).map(function(key) {
  return [key, wordsCount[key]];
});

// 3.2. Sort the array based on the second element

wordsCountArray.sort(function(first, second) {
  return second[1] - first[1];
});


// 4. Display the end result

console.log(wordsCountArray);

The output will show the most used words:

[["was", 2], ["to", 2], ["of", 2], ["her", 2], ["sister", 2], ["the", 2], ["or", 2], ["had", 2], ["it", 2], ["alice", 1], ["beginning", 1], ["get", 1], ["very", 1], ["tired", 1], ["sitting", 1], ["by", 1], ["on", 1], ["bank,", 1], ["and", 1], ["having", 1], ["nothing", 1], ["do", 1], [":", 1], ["once", 1], ["twice", 1], ["she", 1], ["peeped", 1], ["into", 1], ["book", 1], ["reading,", 1], ["but", 1], ["no", 1], ["pictures", 1], ["conversations", 1], ["in", 1], ["...", 1], ["", 1]]

Reading List