All JavaScript Array methods (ES5+)
JS
S
JavaScriptResume of the new Array methods from ECMAScript 2015. For compatibility check: http://kangax.github.io/compat-table/es6/ For Shims: https://github.com/paulmillr/es6-shim
1// Sort *modifies original array
2x = [1,45,3,24,5];
3const decreasingSort = x.sort((a, b) => a < b;); // a = current item in array, b = next item in array
4const increasingSort = x.sort();
5
6// Reverse *modifies original array
7x.reverse();
8
9// Filter *modifies original array
10const evenNumbersOnly = a.filter(num => num%2; );
11
12// Some of the new Array methods are already available in browsers.
13// Map *change every element and also add or remove keys with great ease.
14const array = [{name:1}, {name:2}];
15let normalMap = array.map(s => s.name);
16
17// Map (augmenting the array)
18cons isEven = (num) => num%2 === 0 ? true : false;
19const arrayWithEvenFlag = array.map((item) => {
20 item.isEven = isEven(item.name);
21 return item;
22}
23console.table(arrayWithEvenFlag);
24
25// From
26let newFrom = Array.from(array, s => s.name); //warning, a hole in an array will be undefined
27
28// From Fill (emulate)
29const filledArrayWithFrom = Array.from(new Array(5), () => 'a')
30const filledArrayWithIndex = Array.from(new Array(5), (x,i) => i)
31
32// Fill
33const newArray = [1,2,3];
34const filledArrayWithFill = newArray.fill('a',3); // arr.fill(value, ?start, ?end)
35const fillAllPositions = newArray.fill('a');
36
37
38// Subclassing Arrays
39/*
40class MyArray extends Array {
41 ...
42}
43let instanceOfMyArray = MyArray.from(anIterable);
44*/
45
46// Iterating
47const keys = Array.from(array.keys());
48const entries = Array.from(array.entries());
49
50// Find *like filter but returns 1 item only
51const findFirstNegative = [6, -5, 8].find(x => x < 0);
52const findFirstNegativeIndex = [6, -5, 8].findIndex(x => x < 0);
53
54// Push() //add new elements to the end of array
55// Pop() // remove last element of array
56// Join() // join the elements of the array into a String
57// Concat(arr1,arr2)
58
59// Append an element to an array
60addNewCard = cardInfo => {
61 setCards(cards.concat(cardInfo))
62}
63
64Created on 9/16/2017