Be careful you don’t do this on an empty array: you’ll end up with a single empty
<li>
element!
Conclusion
There’s a lot of power and flexibility built into the JavaScript’s
Array
class, but it can
sometimes be daunting to know which method to use when. Tables
summarize
Array
functionality.
For
Array.prototype
methods that take a function (
find
,
findIndex
,
some
,
every
,
map
,
filter
, and
reduce
), the function that you provide receives the arguments
for each element in the array.
Table 8-1. Array function arguments (in order)
Method
Description
reduce
only Accumulator (initial value, or return value of last invocation)
all
Element (value of current element)
all
Index of current element
all
Array itself (rarely useful)
All
Array.prototype
methods that take a function also take an (optional) value of
this
to be used when the functions are invoked, allowing you to invoke the function
as if it were a method.
Table 8-2. Array content manipulation
When you need to…
Use…
In-place or copy
Create a stack (last-in, first-out [LIFO])
push
(returns new length),
pop
In-place
Create a queue (first-in, first-out [FIFO])
unshift
(returns new length),
shift
In-place
Add multiple elements at end
concat
Copy
Get subarray
slice
Copy
Add or remove elements at any position
splice
In-place
Cut and replace within an array
copyWithin
In-place
Fill an array
fill
In-place
144 | Chapter 8: Arrays and Array Processing