1

I want to create a list of pairs for all possible connections given a list of ids efficiently since these are large lists. Every id should be connected only once and never to itself. They only need to obey the formula n (n - 1) / 2 for connections.

const ids = [1,2,3,4]
const pairs = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

// My first attempt was nested for loops
let pairs = []
for (let i = 0; i < array.length; i++) {
  let pair
  for (let j = i + 1; j < array.length; j++) {
    pair = [array[i], array[j]]
    pairs = [...pairs, pair]
  }
}
mbrimmer
  • 53
  • 1
  • 6
  • 3
    This looks a lot like homework. What have you tried? – Seph Reed Jan 03 '20 at 21:39
  • const array = [1,2,3,4,5] let pairs = [] for (let i = 0; i < array.length; i++) { let pair for (let j = i + 1; j < array.length; j++) { pair = [array[i], array[j]] pairs = [...pairs, pair] } } This was my original solution – mbrimmer Jan 03 '20 at 21:48
  • 1
    Seems like, [this one](https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n) may help. – Yevhen Horbunkov Jan 03 '20 at 21:53

2 Answers2

1
const ids = [1,2,3,4]
const pairs = []

for(let i = 0; i<ids.length-1 ;i++){
    for(let j = i+1; j<ids.length ;j++){
            pairs.push([ids[i],ids[j]]);
    }   
}
console.log(pairs);
CaveCoder
  • 791
  • 3
  • 17
1
const ids = [1, 2, 3, 4];
const result = ids.reduce((output, number, currentIndex) => {
  // if the index is the last one (e.g 4) then it can't be further paired
  if (currentIndex === ids.length - 1) {
    return output;
  }

  // If current number is 1 then the first pairing must be with 2, 
  // that number is at current index + 1
  for (let i = currentIndex + 1; i < ids.length; i += 1) {
    const mate = ids[i];

    output.push([number, mate]);
  }

  return output;

}, []);

console.log(result);