4. The tables

4.1. script [tab-01]
The following script illustrates certain characteristics of the Javascript arrays. These resemble the PHP arrays, but with one major difference: they are manipulated via pointers and are treated as objects.
'use strict';
// an array is an object manipulated via its address
const tab1 = [1, 2, 3];
// address copying
const tab2 = tab1;
// tab1 and tab2 point to the same table
console.log("tab1===tab2 :", tab1 === tab2);
// you can modify the table using either tab1 or tab2
tab2[1] = 10;
console.log("tab1=", tab1);
console.log("tab2=", tab2);
Execution
[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Temp\19-09-01\javascript\tableaux\tab-01.js"
tab1===tab2 : true
tab1= [ 1, 10, 3 ]
tab2= [ 1, 10, 3 ]
Comments
- Line 2 of the results shows that [tab1] and [tab2] are two equal entities, in fact two equal pointers;
- Lines 4 and 5 of the results show that these two pointers point to the same array;
4.2. script [tab-02]
This script shows that the array Javascript is different from arrays in compiled languages.
'use strict';
// table
const tab = [];
console.log("tab=", tab, ", longueur=[", tab.length, "]");
console.log("-------------------------------");
// element initialization
tab[3] = 100;
tab[1] = "huit";
// table
console.log("tab=", tab, ", longueur=[", tab.length, "]");
console.log("-------------------------------");
// toString
console.log("tab.toString=[", tab.toString(), "]");
console.log("-------------------------------");
// the keys to the picture are its indices
for (let key of tab.keys()) {
console.log("clé=[", key, "], valeur=[", tab[key], "]");
}
console.log("-------------------------------");
// table values
for (let value of tab.values()) {
console.log("valeur=[", value, "]");
}
- line 4: an empty array;
- Line 8: An array does not have a fixed size. It is simply a sequence of elements indexed by a number. You can initialize element #3 even if the elements [0, 1, 2] have not yet been defined;
- Lines 16–24: An array Javascript behaves similarly to the array PHP;
Execution
[Running] C:\myprograms\laragon-lite\bin\nodejs\node-v10\node.exe "c:\Temp\19-09-01\javascript\tableaux\tab-02.js"
tab= [] , longueur=[ 0 ]
-------------------------------
tab= [ <1 empty item>, 'eight', <1 empty item>, 100 ] length=[ 4 ]
-------------------------------
tab.toString=[ ,huit,,100 ]
-------------------------------
clé=[ 0 ], valeur=[ undefined ]
clé=[ 1 ], valeur=[ huit ]
clé=[ 2 ], valeur=[ undefined ]
clé=[ 3 ], valeur=[ 100 ]
-------------------------------
valeur=[ undefined ]
valeur=[ huit ]
valeur=[ undefined ]
valeur=[ 100 ]
4.3. script [tab-03]
This script demonstrates various methods of the [tableau] object.
'use strict';
// a table can contain different types of data
const tab = [1, 2, "un", "deux", true, [10, 20], { prop1: 10, prop2: "abc" }];
// console.log can display the contents of an array
show(1);
console.log("tab=", tab);
show(2);
// table path with foreach
tab.forEach(element => {
console.log("élément=", element, typeof (element));
});
show("2b");
// another script to do the same thing
tab.forEach(function (element) {
console.log("élément=", element, typeof (element));
});
show(3);
// table route with for
for (let i = 0; i < tab.length; i++) {
console.log("i=", i, "tab[i]=", tab[i]);
}
show(4);
// change tab[i]
tab[5] = [];
// display
console.log("tab=", tab);
show(5);
// remove the last element
let element = tab.pop(tab);
console.log("élément=", element, "tab=", tab);
show(6);
// add an element to the end of the array
tab.push('xyz');
console.log("tab=", tab);
show(7);
// add an element at the beginning of the array
tab.unshift(1000);
console.log("tab=", tab);
show(8);
// remove the 1st element from the array
element = tab.shift();
console.log("élément=", element, "tab=", tab);
show(9);
// remove element no. 2 from the table
element = tab.splice(2, 1);
console.log("élément=", element, "tab=", tab);
show(10);
// remove two elements from the table, starting with element no. 1
element = tab.splice(1, 2);
console.log("élément=", element, "tab=", tab);
// function
function show(param) {
console.log("[", param, ":::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: ]");
}
Comments
- The difference between arrays PHP and Javascript is illustrated by lines 3 and 24:
- line 3 declares the variable [tab] as a constant;
- line 24 modifies the tab[5] element;
Line 3: it is the pointer pointing to the array that is declared a constant, not the array itself. The array itself can be modified.
- Lines 14–16: The array [tab] is traversed using a method [forEach] from the array [tab]. This method receives as a parameter the definition of a function, which could be called a literal function. This parameter function receives one parameter: the current element of the array [tab]. The function is called for each element of the array. This type of syntax is common in Javascript;
- lines 9–10: a different syntax is used to define the parameter function. Instead of writing:
- function(p1, p2, …, pn){….}
we write:
- (continued)
- (p1,p2, ..,pn)=>{.…}. This is called the “arrow” notation;
- the rest of the code is explained by the comments;
From this script, note that:
- an array is an object referenced by a pointer;
- that this object has methods [forEach, pop, push, shift, unshift];
4.4. script [tab-04]
This script demonstrates other methods of array objects.
'use strict';
// table manipulation method
// a picture
const tab = [];
for (let i = 0; i < 10; i++) {
tab[i] = i * 10;
}
// display
console.log("tab=", tab);
// map
const tab2 = tab.map(element => {
return { prop1: element, prop2: element * element }
});
// display
console.log("tab=", tab);
console.log("tab2=", tab2);
// reduce sans valeur initiale
const somme = tab.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log("somme tab=", somme);
// reduce avec valeur initiale
const somme2 = tab.reduce((accumulator, currentValue) => accumulator + currentValue, 10);
console.log("somme2 tab=", somme2);
// filter
const tab4 = tab.filter((element) => {
if (element > 50) {
return element;
}
});
console.log("tab4=", tab4);
// find
const element1 = tab.find((element) => (element > 20));
console.log("élément1=", element1);
// findIndex
const index1 = tab.findIndex((element) => (element === 20));
console.log("index1 20=", index1);
// indexOf
const index2 = tab.indexOf(30);
console.log("index2 30=", index2);
const index3 = tab.indexOf(31);
console.log("index3 31=", index3);
// lastIndexOf
const index4 = [4, 5, 4, 2].lastIndexOf(4);
console.log("index4 4=", index4);
// sort
const tab5 = [4, 5, 4, 2].sort();
console.log("tab5=", tab5);
// sort inverse
const tab6 = [4, 5, 4, 2].sort((e1, e2) => {
if (e1 > e2) {
return -1;
}
else if (e1 === e2) {
return 0;
} else {
return +1;
}
});
console.log("tab6=", tab6);
Comments
- lines 13-15: the [map] method accepts a transformation function as a parameter. This function is called repeatedly for each element in the array. It is responsible for transforming the element into something else, in this case an object with the properties [prop1, prop2]. The [map] method returns a new array. The original array remains unchanged:
tab= [ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 ]
tab2= [ { prop1: 0, prop2: 0 },
{ prop1: 10, prop2: 100 },
{ prop1: 20, prop2: 400 },
{ prop1: 30, prop2: 900 },
{ prop1: 40, prop2: 1600 },
{ prop1: 50, prop2: 2500 },
{ prop1: 60, prop2: 3600 },
{ prop1: 70, prop2: 4900 },
{ prop1: 80, prop2: 6400 },
{ prop1: 90, prop2: 8100 } ]
- line 20: the method [reduce] takes as a parameter a two-argument function that is called repeatedly for each element of the array. This function takes two arguments:
- [currentValue] is the current element of the array;
- [accumulator] is the last result obtained by the function. If no initial value is specified for this accumulator, then it will be 0;
- the first time the accumulation function is called, it returns [0+tab[0]]. This is the value assigned to the accumulator;
- the second time, it returns accumulator+tab[1], i.e., tab[0]+tab[1];
- the third time, it sets the accumulator to accumulator+tab[2], i.e., tab[0]+tab[1]+tab[2];
- etc. Ultimately, the accumulator will represent the sum of all elements in the array [tab];
- line 26: the method [filter] takes a filtering function as a parameter. This function is called repeatedly for each element of the array and receives that element as a parameter. It must return:
- [true] if the element should be kept;
- [false] otherwise;
- line 33: The method [find] takes a search function as a parameter. This function is called repeatedly for each element of the array and receives the array as a parameter. It must return [true] if the received element satisfies the search criterion. The process then stops. The method [find] therefore returns 0 or 1 element;
- line 36: the method [findIndex] works like the method [find], but instead of returning the found element, it returns its index in the array;
- lines 39, 41: the method [indexOf(valeur)] searches for [valeur] in the array and returns its index, or -1 if it is not found;
- line 44: the method [lastIndexOf(valeur)] works like the method [indexOf(valeur)] but starts its search at the end of the array;
- line 47: the method [sort] without parameters returns an array sorted in natural order (numbers, strings);
- line 50: when the natural order is not suitable, you must pass a function with two parameters (e1, e2) to the method [sort], which returns:
- +1 if e1 should be sorted after e2;
- -1 if e1 should be sorted before e2;
- 0 if both elements should have the same rank;
The function passed as a parameter to the [sort] method is repeatedly called by it to compare two elements of the array;