Skip to content
Advertisement

javascript: return every possible pairs in array

the title explains it all

somehow I’d like to use the method “Combination” that math has, this is the Wikipedia page to be clear: https://en.wikipedia.org/wiki/Combination

I have already found the solution with two loops, I want to do it in one loop

example:

const arr = [1, 2, 3, 4]

function getPairs(arr) {
  /*
  desired return:
  [
    [1, 2], [1, 3], [1, 4],
    [2, 3], [2, 4],
    [3, 4]
  ]
  */
}

Advertisement

Answer

You can use Array.flatMap() to iterate the array, and Array.map() to iterate all items after the current (by slicing from index + 1), and return the pair.

const getPairs = arr => arr.flatMap((a, i) => arr.slice(i + 1).map(b => [a, b]))

const arr = [1, 2, 3, 4]

const result = getPairs(arr)

console.log(result)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement