Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *