Mia
Mia

Reputation: 6531

Data structure to store unique values in javascript

What is the best data type to store unique values only? an array can have duplicates

[one, one, two]

and an object (? maybe wrong terminology) have unnecessary values for my current case

{one: something, two: something, three: something}

Shortly, I need something like this:

{one, two, three}

I am not sure what it is called, or if it does exist in js. Needing some enlightment.

Upvotes: 4

Views: 8265

Answers (3)

dfsq
dfsq

Reputation: 193271

In addition to obvious ways you can always create you own data structure on top of array if you need some more advanced functionality. For example:

function UArray(val) {
    this._values = [];
    if (typeof val !== 'undefined') {
        this.set(val);
    }
}
UArray.prototype.set = function(values) {
    this._values = this._values.concat(values).filter(function(el, i, arr) {
        return arr.indexOf(el) === i;
    });
};
UArray.prototype.get = function() {
    return this._values;
}

var uarr = new UArray();
uarr.set(['one', 'one', 'two']);

alert( uarr.get() );

uarr.set('two');
uarr.set(['three', 'one']);

alert( uarr.get() );

Such a custom data structure could be extended with additional necessary methods, i.e.:

  • remove to remove specific item
  • find to find item's index or -1 if not found,
  • etc.

Upvotes: 0

adeneo
adeneo

Reputation: 318232

The most common way to solve this is to use an array, and just check if it already has the value you want to insert, that way it contains only unique values.

if ( arr.indexOf(value) == -1 ) arr.push(value);

Upvotes: 4

Kuba Jagoda
Kuba Jagoda

Reputation: 5547

You mean a structure called Set, and in the current version of ECMAScript there's no such structure. It will be standarized in the next version, however it's available now in some browsers.

You can emulate set using object, but as you said that also involves unnecessary values. If you don't want to care about them, you can use a library that emulates Set, like http://collectionsjs.com/

Upvotes: 5

Related Questions