2

I have been using this library in my google apps script, particually the Unique function.

So far this has done what I require, if I have two arrays like:

[1,2,3] and [2,3,4], I have been using array1.concat(array2) and the using the unique function, which will return [1,2,3,4].

How can I retrieve unique values which in my example will be [1,4] ?

1

1 Answer 1

3

Try following function, it will return object of distinct, unique and repeated elements.

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

In your case you will get your desired result like console.log(arrays(c).unique) [1,4]

Sign up to request clarification or add additional context in comments.

1 Comment

Now that is a lovely function :-) Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.