How to generate all combinations of elements in a single array in pairs with JavaScript?

Sometimes, we want to generate all combinations of elements in a single array in pairs with JavaScript.

In this article, we’ll look at how to generate all combinations of elements in a single array in pairs with JavaScript.

How to generate all combinations of elements in a single array in pairs with JavaScript?

To generate all combinations of elements in a single array in pairs with JavaScript, we use the array map and flatMap methods.

For instance, we write

const array = ["apple", "banana", "lemon", "mango"];

const result = array.flatMap((v, i) =>
  array.slice(i + 1).map((w) => v + " " + w)
);

console.log(result);

to call slice and map to create all the strings with 2 of the items in array in each string separated by a space.

Then we call flatMap to combine the nested arrays into one flat array.

Conclusion

To generate all combinations of elements in a single array in pairs with JavaScript, we use the array map and flatMap methods.