Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Working answer: <a href="http://jsfiddle.net/y3h9L/" rel="nofollow">http://jsfiddle.net/y3h9L/</a></p> <p>OK, so if I understand the requirement A is a one-dimensional array that is assumed to have an even number of elements in x,y pairs.</p> <pre><code>A = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11] // output should be [ [1,2,3], [9,10,11] ] // but if you add an extra pair that links the two halves, say add 2,11 A2 = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11, 2,11] // then all are related so output should be [ [1,2,3,9,10,11] ] </code></pre> <p>I've made no effort to pretty-up or optimise the following code, but it works:</p> <pre><code>// single dimensional array of x,y pairs var A = [1,2, 1,3, 2,3, 9,10, 9,11, 10,11]; // create a working copy of A so that we can remove elements // and still keep the original A intact. var workingCopy = A.slice(0, A.length), matchedPairs = [], currentMatches, finalCombinations = [], x, y, i, j, tempArray; while (workingCopy.length &gt; 0) { currentMatches = []; currentMatches.push([workingCopy.shift(),workingCopy.shift()]); workingCopyLoop: for (x=0,y=1; x &lt; workingCopy.length;) { for (i=0; i &lt; currentMatches.length; i++){ if (workingCopy[x] === currentMatches[i][0] || workingCopy[y] === currentMatches[i][1]) { currentMatches.push([workingCopy.shift(),workingCopy.shift()]); // go back to the beginning of workingCopyLoop x=0; y=1; continue workingCopyLoop; } } x += 2; y += 2; } matchedPairs.push(currentMatches); } for (i=0; i&lt;matchedPairs.length; i++){ tempArray = []; for (j=0; j&lt;matchedPairs[i].length; j++) { // I assume you have a new enough version of JS that you have Array.indexOf() if (-1 === tempArray.indexOf(matchedPairs[i][j][0])) tempArray.push(matchedPairs[i][j][0]); if (-1 === tempArray.indexOf(matchedPairs[i][j][1])) tempArray.push(matchedPairs[i][j][1]); } finalCombinations.push(tempArray); } for (i=0; i&lt;finalCombinations.length; i++) console.log(finalCombinations[i]); // console.log shows that finalCombinations = [ [1,2,3], [9,10,11] ] </code></pre> <p>If it's not obvious how this works, follow it through with a debugger and/or pencil and paper.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload