With ES6 we gain access to many new array extensions, bellow are a few of them.
//ES6 Array Extensions
//Creates an array of length n but fills it with undefined values
let array = Array(5);
console.log(array);
// array.of() creates array of ... items
let arrayOf = Array.of(5);
let arrayOfTwo = Array.of(5, 111, 52);
console.log(arrayOf);
console.log(arrayOfTwo);
// .from allows us to create a new array based on an old array. also .from allows us to manipulate the old array
// Array.from leaves the origional array unchanged
let arrayFromOld = [32, 33, 11];
console.log(arrayFromOld)
let arrayFromNew = Array.from(arrayFromOld, value => value * 12)
console.log(arrayFromNew)
// .fill takes an origional array, and replaces every value with x
// .fill allows an optional argument
let arrayFill = [1, 2, 3];
let arrayFillArg = [1, 2, 3];
arrayFill.fill(150); // replaces all
arrayFillArg.fill(150, 0, 2); // replaces some with optional argument
console.log(arrayFill);
console.log(arrayFillArg);
// .find returns elements based on meeting a criteria
// expects a function as an argument
// stops after the first match found
let arrayFind = [5, 15, 33];
console.log(arrayFind.find(val => val >= 13)); //Returns : 15
// find an object in an array by one of its properties
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
function isCherries(fruit) {
return fruit.name === 'cherries';
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
let baseArray = [1, 2, 3];
let copyEndArray = [1, 2, 3];
// copyWithin() - allows us to copy a value inside of an array
// expects what to copy, and where to copy it
// **Overwrites** the origional array
//simple copy
console.log(baseArray.copyWithin(1, 2));
//start - end argument copy
console.log(copyEndArray.copyWithin(1, 0, 2));
// array.entries()
// returns a iterator and description of [index , value] of each of the values within the array
let entriesArray = [1, 2, 3];
let it = entriesArray.entries();
for (let element of it) {
console.log(element);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89