dave
dave

Reputation: 1430

Duplicate, Distinct and Unique values in Array JavaScript

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] ?

Upvotes: 2

Views: 260

Answers (1)

nanobash
nanobash

Reputation: 5500

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]

Upvotes: 3

Related Questions