在以下示例数组中查找"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}
];
Run Code Online (Sandbox Code Playgroud)
循环遍历数组并将值放在哈希(对象)中.它是一种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);
}
}
Run Code Online (Sandbox Code Playgroud)