-2

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]
  ]
  */
}

4 Answers4

0

You can use simple for-loops.

function getPairs(arr = []) {
  if (!arr.length) return []
  const pairs = []
  for (let i = 0; i < arr.length; i++) {
     for (let j = i + 1; j < arr.length; j++) {
        pairs.push([arr[i], arr[j]])
     }
  }
  return pairs
}

console.log(getPairs([1, 2, 3, 4]))
Naren
  • 4,152
  • 3
  • 17
  • 28
0

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

For a simple combination algorithm, you need to loop twice through the array. Looking for the math expression, we see that we need to get all elements from the array (let's call this element i) and match all subsequent elements from i with it (let's call those j)

Following it, what we have is something like:

let array = [1, 2, 3, 4];
let results = [];

// Loop through the items on your array (get `i`)
for (let i = 0; i < array.length - 1; i++) {
  // Loop after the current 1st loop item (get `j`) and push them to a new array
  for (let j = i + 1; j < array.length; j++) {
    results.push([array[i], array[j]]);
  }
}

console.log(results);
Renan Souza
  • 905
  • 9
  • 25
  • I'm looking for a way to loop only one time, not two times, and in that just one loop add the items for the current iteration to the result – Hamid Bakhtiari Jan 08 '21 at 12:24
0

Using slice and map

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

console.log(arr.slice(0, -1).map((x, i) => arr.slice(i+1).map(y => [x, y])))
Siva K V
  • 10,561
  • 2
  • 16
  • 29