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

4 Answers 4

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)

Sign up to request clarification or add additional context in comments.

Comments

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]))

Comments

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);

1 Comment

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
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])))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.