使用Underscore.js,我试图在看起来像这样的数组中获取唯一值:

var links = [
    {source: 0, target: 1},
    {source: 0, target: 2},
    {source: 0, target: 3},
    {source: 0, target: 4},
    {source: 0, target: 1},
    {source: 4, target: 0}
];


这样它最终像这样:

var links = [
    {source: 0, target: 1},
    {source: 0, target: 2},
    {source: 0, target: 3},
    {source: 0, target: 4},
];


我想摆脱以相同顺序(0,1 == 0,1)具有相同源和目标对的链接,但是我也想摆脱那些相同但反向的链接(0,4 == 4,0)。

我确定我可以使用双嵌套_.map()来做到这一点,但想看看那里是否有Underscore魔术师有更清洁,更合适的解决方案。

最佳答案

我认为_.uniq是答案。

uniq_.uniq(array, [isSorted], [iteratee])


More info

我相信您可以使用第三个参数(iteratee)提供自定义转换函数,以便在比较之前首先应用。

使用_.uniq(http://jsfiddle.net/muto6zs1/)的示例:

function(item) {
  // sort array of source and target and join it into a delimited string for a unique value
  return [item.source, item.target].sort().join(',');
}

09-16 09:55