Filling an Array with a Specific Value
ES6 brings a welcome new method,
fill
, which allows you to set any number of ele‐
ments with a fixed value (in place). This is particularly useful when used with the
Array
constructor (which allows you to specify the initial size of the array). You can
optionally specify a start and end index if you only want to fill part of the array (nega‐
tive indexes work as expected). Examples:
const
arr
=
new
Array
(
5
).
fill
(
1
);
// arr initialized to [1, 1, 1, 1, 1]
arr
.
fill
(
"a"
);
// arr is now ["a", "a", "a", "a", "a"]
arr
.
fill
(
"b"
,
1
);
// arr is now ["a", "b", "b", "b", "b"]
arr
.
fill
(
"c"
,
2
,
4
);
// arr is now ["a", "b", "c", "c", "b"]
arr
.
fill
(
5.5
,
-
4
);
// arr is now ["a", 5.5, 5.5, 5.5, 5.5]
arr
.
fill
(
0
,
-
3
,
-
1
);
// arr is now ["a", 5.5, 0, 0, 5.5]
Reversing and Sorting Arrays
reverse
is as simple as it gets; it reverses the order of the array in place:
const
arr
=
[
1
,
2
,
3
,
4
,
5
];
arr
.
reverse
();
// arr is now [5, 4, 3, 2, 1]
sort
sorts an array in place:
const
arr
=
[
5
,
3
,
2
,
4
,
1
];
arr
.
sort
();
// arr is now [1, 2, 3, 4, 5]
sort
also allows you to specify a sort function, which can come in quite handy. For
example, there’s no meaningful way to sort objects:
const
arr
=
[{
name
:
"Suzanne"
}, {
name
:
"Jim"
},
{
name
:
"Trevor"
}, {
name
:
"Amanda"
}];
arr
.
sort
();
// arr unchanged
arr
.
sort
((
a
,
b
)
=>
a
.
name
>
b
.
name
);
// arr sorted alphabetically
// by name property
arr
.
sort
((
a
,
b
)
=>
a
.
name
[
1
]
<
b
.
name
[
1
]);
// arr sorted reverse alphabetically
// by second letter of name property
In this example of sort, we’re returning a boolean. However, sort
accepts a number as a return value. If you return a 0, sort will con‐
sider the two elements “equal,” and leave their order intact. This
would allow you, for example, to sort alphabetically except for
words starting with the letter k; everything would be sorted alpha‐
betically, with all k words coming after all j words, and before all l
words, but the k words would be in their original order.
Array Content Manipulation | 135