Note that
concat
only breaks apart arrays you provide it directly; it does not break
apart arrays inside those arrays.
Getting a Subarray
If you want to get a subarray from an array, use
slice
.
slice
takes up to two argu‐
ments. The first argument is where the subarray begins, and the second argument is
where the subarray ends (which does not include the specified character). If you omit
the end argument, it returns everything up to the end of the string. This method
allows you to use negative indices to refer to elements with respect to the end of the
string, which is handy. Examples:
const
arr
=
[
1
,
2
,
3
,
4
,
5
];
arr
.
slice
(
3
);
// returns [4, 5]; arr unmodified
arr
.
slice
(
2
,
4
);
// returns [3, 4]; arr unmodified
arr
.
slice
(
-
2
);
// returns [4, 5]; arr unmodified
arr
.
slice
(
1
,
-
2
);
// returns [2, 3]; arr unmodified
arr
.
slice
(
-
2
,
-
1
);
// returns [4]; arr unmodified
Adding or Removing Elements at Any Position
splice
allows you to do in-place modification of the string, adding and/or removing
elements from any index. The first argument is the index you want to start modify‐
ing; the second argument is the number of elements to remove (use
0
if you don’t
want to remove any elements), and the remaining arguments are the elements to be
added. Examples:
const
arr
=
[
1
,
5
,
7
];
arr
.
splice
(
1
,
0
,
2
,
3
,
4
);
// returns []; arr is now [1, 2, 3, 4, 5, 7]
arr
.
splice
(
5
,
0
,
6
);
// returns []; arr is now [1, 2, 3, 4, 5, 6, 7]
arr
.
splice
(
1
,
2
);
// returns [2, 3]; arr is now [1, 4, 5, 6, 7]
arr
.
splice
(
2
,
1
,
'a'
,
'b'
);
// returns [5]; arr is now [1, 4, 'a', 'b', 6, 7]
Cutting and Replacing Within an Array
ES6 brings a new method,
copyWithin
, that takes a sequence of elements from an
array and copies them, in place, to a different part of the array, overwriting whatever
elements are there. The first argument is where to copy to (the target), the second
argument is where to start copying from, and the final (optional) argument is where
to stop copying from. As with
slice
, you can use negative numbers for the start and
end indexes, and they count backward from the end of the array. Examples:
const
arr
=
[
1
,
2
,
3
,
4
];
arr
.
copyWithin
(
1
,
2
);
// arr is now [1, 3, 4, 4]
arr
.
copyWithin
(
2
,
0
,
2
);
// arr is now [1, 3, 1, 3]
arr
.
copyWithin
(
0
,
-
3
,
-
1
);
// arr is now [3, 1, 1, 3]
134 | Chapter 8: Arrays and Array Processing