Arrays

The main data structure you will use to store one-dimensional data is the JavaScript array. It's used as the main dataset format in most chart types in Chart.js. An array of values is all you need to make a simple bar chart. You can create an array by declaring a list of items within brackets, or simply a pair of opening-closing brackets if you want to start with an empty array:

const colors = ["red", "blue", "green"];
const geocoords = [27.2345, 34.9937];
const numbers = [1,2,3,4,5,6];
const empty = [];

You can then access the items of an array using an array index, which starts counting from zero:

const blue = colors[1];
const latitude = geocoords[0];

Each array has a length property that returns the number of elements. It's very useful to iterate using the array index:

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

You can also loop over the elements of an array using the of operator (introduced in ES2015) when you don't need the index:

for(let color of colors) {
console.log(color);
}

And you can use the forEach() method, which runs a function for each element and also allows access to the index, item, and array inside the function:

colors.forEach(function(i, color, colors) {
console.log((i+1) + ": " + color);
}

Multidimensional arrays are created in JavaScript as arrays of arrays:

const points = [[200,300], [150,100], [100,300]];

You can retrieve individual items like this:

const firstPoint = points[0];
const middleX = points[1][0];

JavaScript provides many ways to extract and insert data into an array. It's usually recommended to use these methods whenever possible. The following table lists useful methods you can use on arrays. Some modify the array; others return new arrays and other types. The examples provided use the colors and numbers arrays as declared previously. Try them out using your browser's JavaScript console:

Method

Description

Example

push(item)

Modifies the array, adding an item to the end.

colors.push("yellow"); 
/*["red", "blue", "green",
"yellow"];*/

pop()

Modifies the array, removing and returning the last item.

const green = colors.pop(); 
// ["red", "blue"];

unshift(item)

Modifies the array, inserting an item at the beginning.

colors.unshift("yellow");
/*["yellow", "red", "blue",
"green"];*/

shift()

Modifies the array, removing and returning the first item.

const red = colors.shift();
// ["blue", "green"];

splice(p,n,i)

Modifies the array, starting at position p. Can be used to delete, insert, or replace items.

const s = numbers.splice(2,3);
// s = [3,4,5]
// numbers = [1,2,6]

reverse()

Modifies the array, reversing its order.

numbers.reverse(); 
// [6,5,4,3,2,1]

sort()

Modifies the array, sorting by string order (if no args) or by a comparator function.

numbers.sort((a,b) => b – a);
// numbers = [6,5,4,3,2,1]

slice(b,e)

Returns a shallow copy of the array between b and e.

const mid = numbers.slice(2,4)
// mid = [3,4]

filter(callback)

Returns new array where the elements pass the test implemented by the function.

const even = numbers.filter(n => n%2==0);
// [2,4,6]

find(function)

Returns the first element that satisfies the test function.

const two = numbers.find(n => n%2==0);
// 2

indexOf(item)

Returns the index of the first occurrence of the item in the array.

const n = numbers.indexOf(3); 
// 4

includes(item)

Returns true if an array contains the item among its entries.

const n = numbers.includes(3); 
// true

lastIndexOf(item)

Returns the index of the last occurrence of the item in the array.

const n = colors.lastIndexOf("blue"); 
// 1

concat(other)

Returns a new array that merges the current array with another.

const eight = numbers.concat([7,8]);
// [1,2,3,4,5,6,7,8]

join()

join(delim)

Returns a comma-separated string of the elements in the array (an optional delimiter may be used).

const csv = numbers.join();
// "1,2,3,4,5,6"
const conc = numbers.join("");
// "123456"

map(function)

Returns a new array with each element modified by the function.

const squares = numbers.map(n => n*n);
// [1,4,9,16,25,36]

reduce(function)

Returns the result of an accumulation operation using the values in the array.

const sum =
numbers.reduce((a, n) => a + n);

forEach(function)

Executes the provided function once for each element in the array.

const squares = [];
numbers.forEach(n => squares.push(n*n)
// squares = [1,4,9,16,26,36]
JavaScript functions for array manipulation

Besides arrays, ES2015 also introduced two new data structures: Map, an associative array with key-value pairs, easier to use than simple objects, and Set, which doesn't allow repeated values. Both can be transformed to and from arrays.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset