minte9
LearnRemember



Order

An array is a special data structure, to store ordered collections.
 
/**
 * Arrays are used to store ordered collections
 * Objects are for storing key:value collections 
 * An array can store elements of any type
 */

let vars = [
    "Apple", 
    "Orange", 
    () => {
        console.log('Hello World');
    },
    {name: 'John'}, // comma allowed
];
console.log(vars[1]);       // Orange
console.log(vars[3].name);  // John
vars[2]();                  // Hello World

A = ["Apple", "Orange"];
B = ["Apple", "Orange"];
C = ["Apple", "Orange"];
D = ["Apple", "Orange"];

A.pop();                        // extract last
B.push("Pear");                 // append at end
C.shift();                      // extract first
D.unshift("Orange", "Lemon");   // add to begining

console.log(A); // Apple
console.log(B); // Apple, Orange, Pear
console.log(C); // Orange
console.log(D); // Orange, Lemon, Pear, Orange

Object

An array is an object and behaves like an object.
 
/**
 * There are only eight data types in Javascript, and ...
 * an array is just a special type of object
 * The engine stores elements in order, to work realy fast
 */

let A = ['Banana'];
let B = A;
console.log(A === B); // true

B.push("Orange");
console.log(A); // Banana, Orange

Matrix

Arrays can have items that are also arrays.
 
/**
 * Multidimensional arrays
 * 
 * The for ... of is the prefered way to loop
 * The for ... in is optimize for objects, 10-100 slower
 * 
 * Length, actually not the count of values in array, 
 * is the greatest numeric index plus one
 */

let matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
console.log(matrix[1][1]); // 5 (central element)


for (let i=0; i<matrix.length; i++) {
    console.log(matrix[0][i]); // 1 4 7
}

for (let item of matrix) {
    console.log(item[0]); // 1 4 7
}

for (let key in matrix) { // slower
    console.log(matrix[key][0]); // 1, 4, 7
}

matrix.forEach((val, key, arr) => {
    console.log(val.toString());
        // 1, 2, 3
        // 4, 5, 6
        // 7, 8, 9
});

let vars = ["Orange"];
vars[123] = "Apple";
console.log(vars.length); // 124 - Look Here

Methods

Most useful and often used (filter, map, sort).
 
/**
 * Array methods
 * 
 * filter() map() sort()
 */

let A = [
    {id: 1, user: 'John'},
    {id: 2, user: 'Pete'},
    {id: 3, user: 'Marry'},
];
let B = A.filter(item => item.id < 2);
let C = ["Bilbo", "Gandalf"];
let D = C.map(item => item.length);
let E = [
    {id: 12, user: 'John'},
    {id: 2, user: 'Pete'},
    {id: 3, user: 'Marry'},
];
E.sort((a, b) => a.id - b.id);

console.log(B);     // {id: 1, user: 'John'}
console.log(D);     // [5, 7]
console.log(E[0]);  // {id: 2, user: 'Pete'},



  Last update: 453 days ago