Array
Array
Simple Array Methods
slice()
It does not change the original array.
splice()
It changes the original array.
1
2
3let arr = ['a', 'b', 'c', 'd', 'e'];
console.log(arr.splice(2)); //(3) ['c', 'd', 'e']
console.log(arr); //(2) ['a', 'b']reverse()
Change!
concat()
1
let arr = arr1.concat(arr2);
join()
at()
Similar to []
1 | let arr = ['a', 'b', 'c', 'd', 'e']; |
But at()
can use negative index. So if we want the last element of an array.
1 | let arr = ['a', 'b', 'c', 'd', 'e']; |
And when you use method chaining.
forEach()
You can not break or continue it.
We can also use it in Maps and Sets
map()
Map returns a new array containing the results of applying an operation on all original array elements
filter()
filter returns a new array containing the array elements that passed a specified test condition
reduce()
reduce boils (‘reduces’) all array elements down to one single value(e.g. adding all elements together
1 | const maxMov = movements.reduce( |
find()
findIndex()
includes()
some()
1 | console.log(movements.some(mov => mov > 0));//true |
every()
Similar to some(), but need all elements satisfy the condition
flat()
1 | let arr = [[1, 2, 3], 4, 5, [6, [7, 8]]]; |
flatMap()
Similar to map(), but flat its result.
sort()
Change the original array.
1 | let movements = [200, 450, -400, 3000, -650, -130, 70, 1300]; |
new Array()
fill()
1 | const x = new Array(7); |
Array.from()
1 | const x = Array.from({ length: 7 }, () => 1); |
1 | const x = Array.from({ length: 7 }, (cur, i) => i + 1); |
Turn NodeList into an Array.
1 | const movementsUI = Array.from(document.querySelectorAll('.movements__value')); |
Which Array Method to Use?
To Mutate Original Array
- Add to original
push()
(end)unshift()
(start)
- Remove from original
pop()
(end)shift()
(start)splice()
(any)
- Others
reverse()
sort()
fill()
A New Array
- Computed from original
map()
- Filtered using condition
filter()
- Portion of original
slice()
- Adding original to other
concat()
- Flattening the original
flat()
flatMap()
An Array index
- Based on value
includes()
- Based on test condition
findIndex()
An Array Element
- Based on test condition
find()
Konw if array includes
- Based on value
includes()
- Based on test condition
some()
every()
A New String
- Based on separator string
join()
To Transform to Value
- Based on accumulater
reduce()
To Just Loop Array
- Based on callback:
foreach()