在JavaScript对象数组中查询唯一属性值的最佳方法是什么?

4
在下面的示例数组中,查找“foo”的所有可能值的最佳(或最快)方法是什么。
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个回答

6

遍历数组并将值放入哈希(对象)中。这是一个O(n)算法。

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);
    }
}

请注意,算法无法区分具有相同字符串表示形式的值,例如5和'5'。 - Christoph

3
这是 Chetan 的答案的类型安全版本:

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]);
    }
}

然而对于对象来说,它仍然会出现问题:只要未覆盖toString()方法,所有对象都共享字符串表示形式'[object Object]'


不错的技巧。你也可以查看 http://code.google.com/p/jshashtable/,以获取JavaScript中真正的哈希表实现。 - Chetan S
@Chetan:我实际上有自己的实现,就在这里:http://mercurial.intuxication.org/hg/js-hacks/raw-file/tip/map.js;另请参见https://dev59.com/UXRC5IYBdhLWcg3wOeaB#383540。 - Christoph

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接