Function to display every element of array with each other element once

2252 views javascript
6

How do I display every element in an Array with each other element once, but not itself?

For example:

var myArray:any = "a b c d"

And then display:

a,b
a,c
a,d

b,a
b,c
b,d

etc.

answered question

5 Answers

6

A for in for works fine.

var myArray = "a b c d".split(' ');

for (let first of myArray) {
  for (let second of myArray) {
    if (first !== second) {
      console.log(`${first},${second}`)
    }
  }
}

posted this
9

Try

function f (arr) {
  arr.forEach(function(e) {
    arr.forEach(function(e2) {
      if (e === e2) return;
      var str = e + "," + e2;
      // print str
    });
  });
}

f("a b c d".split(' '));

posted this
13

You could also use dankogai/js-combinatorics like this:

cmb = Combinatorics.combination(['a','b','c','d'], 2);
while(a = cmb.next()) console.log(a);
//  ["a", "b"]
//  ["a", "c"]
//  ["a", "d"]
//  ["b", "c"]
//  ["b", "d"]
//  ["c", "d"]

posted this
1

"a b c d".split(' ').map((el, idx, arr)=>{ 

  let elIdx = arr.indexOf(el);
  let rest = arr.slice(0,elIdx).concat(arr.slice(elIdx+1)).map((l)=> console.log(`${el},${l}`) );

});

posted this
13

for this you can do imbrication of map fonctions, but you do have to work with arrays

here an exemple:

const myArray = ["a", "b", "c", "d", "e", "f", "g"]

// forEach accept one first param x current value 
// second param is optional xi index of value
// third param is optional too and it refer the array itself
myArray.forEach( (x, xi, myArr) => {
      myArr.forEach( (y, yi) => {
        if(xi !== yi) { console.log(`${x}, ${y}`); }
      });
    });

posted this

Have an answer?

JD

Please login first before posting an answer.