Arrays
Arrays are lists of items.
var anotherAmazingArray = ["Three","Bs","in","a","bucket"];
Get, Add and Remove elements from an array
Array.indexOf()
Array.find()
Array.find() method get the first element that satisfies a condition.
const array = [1,2,3,4,5]
let c = array.find( x => x % 2 === 0 )
// 2
Array.filter()
Array.filter gets all the elements that satisfy a condition
const array = [1,2,3,4,5]
let d = array.filter( x => x%2 === 0 )
// [2,4]
Array.slice()
Array.slice gets a subset of the array from start index to the end index ( end not included )
const array = [1,2,3,4,5]
let foo = array.slice(1,4)
// [2,3,4]
Array.splice(startIndex, deleteCount, ... items_to_add)
let letters = [ 1,2,3,4,5]
letters.splice(1,0, 6,9)
// letters : [1,6, 9,3,4,5]
Array.push() <- push an element to the end of the array
Array.pop() <- takes the last element
Array.shift() <- takes the first element
Array.concat() <- makes a new array
Array.map()
Array.forEach()
// Using forEach()
let arr2 = 11, 2, 31;
arr2. forEach((e) => {
console.log(e * 2);
}) ;
//Does not return anything
// Output: 2 4 6
Sort an Array
Out of the box it does an alphabetical sort.
To numeric sort - then use a function.
let array = ['c', 'e', 'a', 't'];
//sort the array
array.sort();
console. log(array);
// Output: ['a', 'c', 'e', 't']
//reverse the array
array.reverse();
console.log(array);
// Output: ['t', 'e', 'c', 'a']
Reverse an Array
Array destructuring
const fruits = ['apple', 'pear', 'bannana' ]
const [a,b,c] = fruits
// a is 'apple'
// b is 'pear'
// c is 'bannana'
How to convert an array-like object into an array
var arrayLike = {0: 'a', 1: 'b', 2: 'c', length: 3}
var foo = Array.from(arrayLike)
This just takes the values from the key-value pairs.
---
var foo = [...arrayLike]
----
foo = {0:'aaa', 1:3, length:2} <- the length is important
var bar = Array.from(foo)
// bar is ["aaa", 3]
//Array.prototype.slice.call)
var arrayLike = {0:'a', 1:'b', 2:'с', length:3}
var array3 = Array.prototype.slice.call(arrayLike)
console.log(array3)
// Output: ['a','b','c']