flatMap 现在在 ECMAScript 中可用,有一个非常简单且可读的选项可以在 Javascript 中查找列表中的项目对,而无需循环:
const pairs = (a) => {
return a.flatMap( (x) => {
return a.flatMap( (y) => {
return (x != y) ? [[x,y]] : []
});
});
}
调用pairs([1,2,3])会输出:
[ [ 1, 2 ], [ 1, 3 ], [ 2, 1 ], [ 2, 3 ], [ 3, 1 ], [ 3, 2 ] ]
简单、易读且实用。
编辑:我最初将这个问题读作“如何获得所有对”,我认为它包括反向对,上面的例子就是这样。要返回没有倒序对的列表,我们可以用reduce() 取出这些:
const isInArray = (a, value) => {
if (
a.map((x) => {
if (x.toString() == value.toString()) return true;
}).includes(true)
){
return true;
}
};
const reducedPairs = (a) => {
return a.flatMap( (x) => {
return a.flatMap( (y) => {
return (x != y) ? [[x,y]] : []
});
}).reduce( (unique, current) => {
if (!isInArray(unique, current.slice().reverse())) unique.push(current);
return unique;
}, []);
}
请注意,这使用字符串比较来检查数组是否相等,因为[1,2] == [1,2] 是false。这适用于原始问题中的用例,但对于更复杂的示例,可能需要另一种检查重复项的方法。