2

如何将 Array 中的每个元素与其他元素一起显示一次,但不显示其本身?

例如:

var myArray:any = "a b c d"

然后显示:

a,b
a,c
a,d

b,a
b,c
b,d

等等

4

5 回答 5

3

一个 for in for 工作正常。

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

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

于 2018-11-04T22:41:16.873 回答
0

尝试

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(' '));
于 2018-11-04T22:44:11.277 回答
0

你也可以像这样使用dankogai/js-combinatorics

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"]
于 2018-11-04T22:44:42.020 回答
0

"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}`) );

});

于 2018-11-04T22:48:55.503 回答
0

为此,您可以使用地图功能,但您必须使用数组

这里有一个例子:

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

于 2018-11-04T22:50:55.637 回答