Array Introduction:
const array = ["item1", "item2", "item3"];
let accessArrayWithBracketNotation = array[0]; // "item1"
.length // shows number of items in an array
let accessLastItem = array[array.length - 1]; // "item3"
array[0] = "firstItem"; // changes item1 to firstItem
Array with different data types:
const arrayList = ['apple', 3, true, ['John', 'Doe'], {'firstName': 'John', 'lastName': 'Smith'}];
Spread Operator:
...arr // the spread operator expands an array
const array = [1, 2, 3];
const obj = { ...array }; // { 0: 1, 1: 2, 2: 3 }
Array Destructuring:
let cars = ['ferrari', 'tesla', 'cadillac'];
let [car1, car2, car3] = cars;
console.log(car1, car2, car3); // Prints: ferrari tesla cadillac
Looping Through an Array:
const students = ["Jan", "Tim", "Sara", "Mila"];
let items = ''
for (let i = 0; i < students.length; i++){
console.log( students[i] );
items += `<li>${student[i]}</li>`;
}
Arrays can hold multiple values.
const map = arr.map( (value, index ,array)=> {
return value * 2;
});
Creates a new array by performing a function on each element, doesn’t change original.
const numbers = [1, 3, -4, 9, -1];
numbers.filter((value, index, array)=> {
return value > 0
}); // [1, 3, 9]
Creates a new array with elements that pass a test.
const nums = [0, 1, 2, 3, 4];
console.log(nums.indexOf(0)); // Expected output: 0
Returns the first index at which a given element can be found in the array.
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found); // Expected output: 12
Returns the value of the first element that passes a test.
.toString() // converts an array to a string
.join() // join all array elements into a string, join(“ * ”) - to join with * between each
.pop() // removes last element in an array, can be stored inside a variable
.push() // adds new element in an array, at the end. arr.push(“str”) (multiple elements use comma)
.shift() // removes the first element in an array
.unshift() // adds new element at the beginning arr.unshift(“str”) (use comma for multiple elements)
arr[index] = “” // to change a specific element in an array
.concat() // const array3 = array1.concat(array2); merge arrays together
.flat() // arr1.flat(); unnests nested arrays once in an array
.splice(start, deleteCount, item0, item1, ...) // remove and replace items
.slice(start, end) // makes a shallow copy of an array
.reverse() // reverses items in an array
.sort()
To sort an array alphabetically or numerically, lowest to highest:
points.sort(function(a, b){return a - b});
To sort an array in a random order:
points.sort(function(){return 0.5 - Math.random()});
To find the highest number:
function myArrayMax(arr){return Math.max.apply(null, arr);}
Some methods to be used on arrays.
const numbers = [1, 2, 3, 4, 5];
const added = numbers.reduce( (accumulator, value, index, array)=> {
return accumulator + value
});
console.log(added); // 15
.reduceRight() // the same but from right to left
Runs a function on each element to produce (reduce it to) a single value, can accept initial value. Accumulator = the initial value / previously returned value.
const nums = [0, 1, 2, 3, 0];
console.log(nums.lastIndexOf(0)); // Expected output: 4
Same as indexOf but starts at the end.
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // Expected output: 3
Returns the index of the first element that passes a test.
const array1 = [1, 2, 3];
array1.includes(2); // Expected output: true
Returns true if value is present.
arr.forEach( (value, index, array)=> {
text += value + “<br>”;
});
Executes a provided function once for each array item.
const nonFlat = [1,2,3,[4,5,6]];
const flat = nonFlat.flatMap(num => num);
console.log(flat); // [1,2,3,4,5,6]
Similar to map, creates a new map array, but then flattens (de-nests) it.
.every( (value, index, array)=> {
return value > 18;
});
// if all array items over 18 returns true
Returns true if all elements pass a test, otherwise returns false.
const array = [1, 2, 3, 4, 5];
const even = (element) => element % 2 === 0; // Checks whether an element is even
console.log(array.some(even)); // Expected output: true
Returns true if at least one element passes a test, otherwise false.
Array.from('ABCDEF'); // ["A", "B", "C", "D", "E", "F"]
Returns an Array object from any object with a length property or any iterable object.
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// Expected output: 0
// Expected output: 1
// Expected output: 2
Returns a new array object that contains the keys for each index in the array.
const array = ["a", "b", "c"];
const arrayEntries = array.entries();
for (const element of arrayEntries) {
console.log(element);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']
Returns a new array iterator object that contains the key/value pairs for each index in the array.