4

What would be the best (or fastest) way to find all the possible values of "foo" in the following example array.

var table = [
    {foo: 0, bar:"htns", stuff:123},
    {foo: 2, bar:"snhn", stuff:156},
    {foo: 5, bar:"trltw", stuff:45},
    {foo: 5, bar:"lrctm", stuff:564},
    //few thousand lines later
    {foo: 2596, bar:"cns", stuff:321},
    {foo: 2597, bar:"gcrl", stuff:741}
];

2 Answers 2

6

Loop through the array and put the values in a hash (object). It is a O(n) algorithm.

var result = {};
for(var i=0; i<table.length; i++) {
    result[table[i].foo] = 1; //the value can be anything
}

//now read back the unique values
for (i in result) {
    if (result.hasOwnProperty(i)) { 
        console.log(i);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

note that the algorithm won't discern between values with identical string representation, eg 5 and '5'
3

This is a typesafe version of Chetan's answer:

var result = {};
for(var i = 0; i < table.length; ++i) {
    var value = table[i].foo;
    result[(typeof value) + ' ' + value] = value;
}

for(id in result) {
    if(result.hasOwnProperty(id)) { 
        console.log(result[id]);
    }
}

It will still break for objects, though: as long as the toString() method hasn't been overwritten, they all share the string representation '[object Object]'.

2 Comments

Nice trick. You could also look into code.google.com/p/jshashtable for a true hashtable implementation in javascript.
@Chetan: I actually have my own implementation lying around: mercurial.intuxication.org/hg/js-hacks/raw-file/tip/map.js ; see also stackoverflow.com/questions/368280/…

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.