DEV Community

Cover image for JS Fundamentals: Arrays
Ivana
Ivana

Posted on

JS Fundamentals: Arrays

Introduction

Arrays are a simple data structure for storing lots of similar items. Arrays are used to store multiple values in a single variable, and variable can store only one value. All programming languages uses arrays.

Common operations

Create Arrays

An Array is a list, with the items listed in a particular order, surrounded by square brackets [].
To declare an array, define the variable type with square brackets:

['This', 'is', 'an', 'array', 'of', 'strings.'];

The members or elements in an Array can be data of any type in JavaScript:

['Hi there!', 502, null, NaN];

Arrays are ordered, meaning that the elements in them will always appear in the same order. So for example the Array [1, 2, 3, 4] is different from the Array [4, 3, 2, 1].

Just like any other type of JavaScript data, we can assign an Array to a variable:

const primes = [2, 3, 5, 7, 11, 13,]; 
const shows = ['Game of Thrones', 'True Detective', 'Empire'];
Enter fullscreen mode Exit fullscreen mode

We can find out how many elements an Array contains by checking the Array's built-in length property:

const myArray = ['This', 'array', 'has', 5, 'elements'];
myArray.length;
// => 5
Enter fullscreen mode Exit fullscreen mode
let fruits = ['Apple', 'Banana']
console.log(fruits.length)
// 2
Enter fullscreen mode Exit fullscreen mode

Access the Elements in an Array

Every element in an Array is assigned a unique index value that corresponds to its place within the collection. The first element in the array is at index 0, the fifth element at index 4, and the 128th element at index 127, and all can be manipulated with various methods.

Alt Text

To access an element, we use the computed member access operator - "square brackets", most people just call it bracket notation or the bracket operator.

const winningNumbers = [32, 9, 14, 33, 48, 5];
// => undefined

winningNumbers[0];
// => 32

winningNumbers[3];
// => 33
Enter fullscreen mode Exit fullscreen mode

Add Elements to an Array

JavaScript allows us to manipulate the members in an Array with .push() and .unshift() methods.

With the .push() method, we can add elements to the end of an Array:

const fruits = ["Apple", "Banana", "Orange"];

fruits.push("Lemon");
// => 4

fruits;
// => ["Apple", "Banana", "Orange", "Lemon"]

We can also .unshift() elements onto the beginning of an Array:

const cities = ['New York', 'San Francisco', 'Atlantic City'];

cities.unshift('Los Angeles');
// => 3

cities;
// => ["Los Angeles", "New York", "San Francisco", "Atlantic City"]
Enter fullscreen mode Exit fullscreen mode

Remove Elements from an Array

As complements for .push() and .unshift(), respectively, we have .pop() and .shift().

The .pop() method removes the last element in an Array, destructively updating the original Array:

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

days.pop();
// => "Sun"

days;
// => ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
Enter fullscreen mode Exit fullscreen mode

The .shift() method removes the first element in an Array, also mutating the original:

const days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

days.shift();
// => "Mon"

days;
// => [Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
Enter fullscreen mode Exit fullscreen mode

Spread Operator - Important feature of ES6

ECMAScript 6 (ES6 or ECMAScript 2015 ) was the second major revision to JavaScript. ES2015 introduced the spread operator, which looks like an ellipsis: ....

The spread operator allows us to spread out the contents of an existing Array into a new Array, adding new elements but preserving the original:

const coolCities = ['New York', 'San Francisco'];

const allCities = ['Los Angeles', ...coolCities];

coolCities;
// => ["New York", "San Francisco"]

allCities;
// => ["Los Angeles", "New York", "San Francisco"]
Enter fullscreen mode Exit fullscreen mode

Arrow Functions - Important feature of ES6

Arrow functions allow a short syntax for writing function expressions. You don't need the function keyword, the return keyword, and the curly brackets.

// ES5
var x = function(x, y) {
   return x * y;
}

// ES6
const x = (x, y) => x * y;
Enter fullscreen mode Exit fullscreen mode

map, reduce, filter methods

These are the collection-processing methods you should memorize and practice heavily.

Now that you have written map and reduce, here's the big reveal: JavaScript already has these methods built into its Array data type!

Use map to Transform an Array

[10, 20, 30, 40].map(function(a) {
  return a * 2;
}); //=> [20, 40, 60, 80]
Enter fullscreen mode Exit fullscreen mode

Use reduce to Reduce an Array to a Value

[10, 20, 30, 40].reduce(function(memo, i) { return memo + i }) //=> 100
[10, 20, 30, 40].reduce(function(memo, i) { return memo + i }, 100) //=> 200
Enter fullscreen mode Exit fullscreen mode

JavaScript loves functions and by being able to pass functions around comfortably, we can take advantage of methods that JavaScript gives us! Given what you know about writing your own map and reduce functions, read the JavaScript documentation and make sure you know how to use the versions JavaScript provides you: map, reduce

filter() method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

The syntax snippet is provided as:

let newArray = arr.filter(callback(currentValue[, index[, array]]) {
  // return element for newArray, if true
}[, thisArg]);

Enter fullscreen mode Exit fullscreen mode
Parameters:

callback - the function is a predicate, to test each element of the array. Return a value that coerces to true to keep the element, or to false otherwise. callback is invoked with three arguments:

the value of the element
the index of the element
`the Array object being traversed

It accepts three arguments:

currentValue
The current element being processed in the array.
Here, we're told that on an Array (arr), we add a .filter, and then, between (), we provide a callback and a thisArg.

index Optional
The index of the current element being processed in the array.

array Optional
The array filter was called upon.

thisArg Optional
Value to use as this when executing callback.

JavaScript will move through the Array that filter() was invoked on and pass the element, the index of that element, and the whole array to the callback.

We don't have to add parameters for index or array, or element even. We can name our parameters whatever we like. JavaScript always makes those 3 arguments available to our callback. See examples below to see how we can play with this. Now, what happens in a callback?

The documentation tells us:
Function is a predicate, to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments

This function runs and has access to the parameters we just explained.

If the call to callback returns true, that element will be added to an invisible "keeper" Array; else, it's left out.

We can use the element or the array or the index or (more typically) some interaction between them to create an expression that returns a Boolean value from the callback.

Example: Find all prime numbers in an array

The following example returns all prime numbers in the array

Alt Text

To learn more, check the official MDN documentation and JS examples:

To connect please check my Github, LinkedIn or Twitter.

Thank you for reading!

Top comments (0)