To generate all combinations of elements in a single array in pairs with JavaScript, we call the flatMap
and slice
method.
For instance, we write
const array = ["apple", "banana", "lemon", "mango"];
const result = array.flatMap((v, i) =>
array.slice(i + 1).map((w) => v + " " + w)
);
to call array.flatMap
with a callback that returns a sliced version of the array with slice
with items from index i + 1
to the end of the array
.
And then we call map
on the sliced array and combined the item v
and w
into a string.
flatMap
will flatten the arrays returned into a single level array with the results.