【问题标题】:Duplicate, Distinct and Unique values in Array JavaScript数组 JavaScript 中的重复、不同和唯一值
【发布时间】:2014-04-13 08:42:16
【问题描述】:

我一直在我的 google 应用程序脚本中使用这个 library,尤其是 Unique 函数。

到目前为止,这已经完成了我的要求,如果我有两个数组,例如:

[1,2,3][2,3,4],我一直在使用array1.concat(array2) 和唯一的函数,它会返回[1,2,3,4]。

如何检索在我的示例中为 [1,4] 的唯一值?

【问题讨论】:

标签: javascript arrays google-apps-script


【解决方案1】:

试试下面的函数,它会返回不同、唯一和重复元素的对象。

var a = [1,2,3], b = [2,3,4];
var c = a.concat(b);

function arrays( array ) {
    var distinct = [], unique = [], repeated = [], repeat = [];

    array.forEach(function(v,i,arr) {
        arr.splice(i,1);
        ( distinct.indexOf(v) === -1 ) ? distinct.push(v) : repeat.push(v);
        ( arr.indexOf(v) === -1 ) ? unique.push(v) : void 0;
        arr.splice(i,0,v);
    });

    repeat.forEach(function(v,i,arr) {
        ( repeated.indexOf(v) === -1 ) ? repeated.push(v) : void 0;
    });

    repeat = [];

    return {
        "distinct" : distinct,
        "unique"   : unique,
        "repeated" : repeated
    };
}

console.log(arrays(c));

DEMO

在你的情况下,你会得到你想要的结果,比如console.log(arrays(c).unique) [1,4]

【讨论】:

  • 现在这是一个可爱的功能 :-) 谢谢
猜你喜欢
  • 2020-09-20
  • 1970-01-01
  • 2022-12-22
  • 2019-03-24
  • 1970-01-01
  • 2010-12-29
相关资源
最近更新 更多