Dorokhov.codes
Array
All arrays are copied by link.
Creating an array
const arr = [10, 22, 12, 54];
const arr = [10, 'hello', 12, {answer: 'yes'}];
Delete the third element:
delete arr[2];
Basic methods
arr.pop(); // Remove the last element.
arr.push(18); // Add an element to the end.
arr.shift(); // Remove the first element.
arr.unshift(23); // Add an element to the beginning.
Working with strings
// Join elements into a string:
const str = arr.join(', ');
// Split string using a delimeter:
const arr = str.split(', ');
Sorting
// The method changes the array.
arr.sort(); // alphabetically.
arr.sort((a, b) => a - b); // for sorting numbers.
arr.reverse(); // change the order of the elements.
Replacing elements
// Remove `count` elements starting from `index`
// and replace them to element1...
arr.splice(index, count, element1...);
Copying
Copy part of an array:
arr.slice(begin, end);
Copy all the array:
const newArr = arr.slice(); // When we need to create an array copy instead of copying a link.
Copying an array using the spread operator:
const newArr = [...arr1]; // Way to copy an array.
Concatenating
arr.concat(arr2);
Using the spread
operator:
const arr1 = ['one', 'two', 'three'];
const arr2 = ['apple', 'watermelon', 'cherry'];
const result = [...arr1, ...arr2, 'table'];
Iterating
Classic for
:
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
The for-of
:
// Comparing to forEach() using this
// method gives ability to use break and continue.
for (let item of arr) {
console.log(item);
}
The forEach
method:
arr.forEach(function(item, index, array) {
console.log(`${index}: ${item} inside of ${array}`);
});
The filter()
method:
const newArray = arr.filter(item => {
return item.length < 10;
});
The map()
method:
const newArray = arr.map(item => item.toLowerCase());
The some()
method:
const someElementIsNumber = arr.some(item => typeof(item) === 'number'); // returns boolean
The every()
method:
const everyElementIsNumber = arr.every(item => typeof(item) === 'number'); // returns boolean
The reduce()
method:
const newArray = arr.reduce((sum, item) => sum + item);
// Initial value of sum is 9.
const newArray = arr.reduce((sum, item) => sum + item, 9);
Create an array from a pseudo-array:
const a = Array.from(pseudoArray);
Destructuring assignment
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
let arr = ["John", "Smith"]
let [firstName, surname] = arr;
Spreading
const arr1 = ['one', 'two', 'three'];
someFunction(...arr1); // Function that receives three arguments.
Checks
Array.isArray(someVar);