我一直在谷歌应用程序脚本中使用这个库,尤其是Unique函数。
到目前为止,这已经完成了我的要求,如果我有两个数组,比如:
[1,2,3]
和[2,3,4]
,我一直在使用array1.concat(array2)
和使用唯一函数,它会返回[1,2,4]。
如何检索在我的示例中为[1,4]
的唯一值?
尝试以下函数,它将返回具有不同、唯一和重复元素的对象。
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));
演示
在您的情况下,您将获得所需的结果,如console.log(arrays(c).unique)
[1,4]