michael-h.dk

Multimedia Designer and Web Developer

Photo by Samuel Zeller from Unsplash.com

Array Cardio 1

From theWikipedia article:

In computer science, an array data structure, or simply an array, is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called one-dimensional array.

In all programming languages there are multiple ways to work with an array. Most of the time it is happening invisible to the user, but here I will try to show how you can use the methods of working with arrays in JavaScript.

Inventors

The first dataset I work on, is an array of inventors with firstname, lastname, year of birth and year of death.

The dataset comes from javascript30.com.

1. Array.prototype.filter()

From MDN web docs:

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

Find the inventors born between two years provided by the user

const filteredInventors = inventors.filter(inventor => (inventor.year >= yearOne && inventor.year <= yearTwo));

Show inventor born in a time periode

2. Array.prototype.map()

From MDN web docs:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Make an array of first- and lastnames of the inventors

const onlyNames = inventors.map(inventor => `${inventor.first} ${inventor.last}` );

3. Array.prototype.sort()

From MDN web docs:

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points. The time and space complexity of the sort cannot be guaranteed as it is implementation dependent.

Sort the inventors based on user input

sortedInventors = inventors.sort((a, b) => a.last > b.last ? 1 : -1);

Choose how to sort inventors:

4. Array.prototype.reduce()

From MDN web docs:

The reduce() method executes a reducer function (that you provide) on each member of the array resulting in a single output value.

Find the toltal years all the invnetors lived

const totalAge = inventors.reduce((total, inventor) => { return total + (inventor.passed - inventor.year)}, 0);

 reduce() 2

The reduce() function can also be used to count all instances of values in an object.

The dataset for this example:

const data = ['car', 'car', 'truck', 'truck', 'bike', 'walk', 'car', 'van', 'bike', 'walk', 'car', 'van', 'car', 'truck', 'pogostick'];