簡體   English   中英

在javascript / node.js中迭代對象數組的有效方法

[英]Efficient way of iterating over a array of objects in javascript/node.js

我已經定義了一個對象

var Person = function(name,age,group){
this.name = name,
this.age = age,
this.group = group
}

var ArrPerson = [];
ArrPerson.push(new Person("john",12,"M1"));
ArrPerson.push(new Person("sam",2,"M0"));

現在我需要一種有效的機制來識別ArrPerson對象數組是否包含特定名稱?

我知道我們可以使用for循環和check來迭代數組。假設數組很大,有沒有其他有效的方法呢?

您可以使用數組過濾器或查找方法

ArrPerson.find(p=>p.name=='john')
ArrPerson.filter(p=>p.name=='john')

find方法從開始時搜索數組,並在找到一個匹配的元素時停止。在最壞的情況下,被搜索的元素是數組中的最后一個或者它不存在,這個方法將執行O(n)。這個意味着此方法將執行n次檢查(n作為數組的長度),直到它停止。

filter方法總是執行O(n),因為每次它將搜索整個數組以找到匹配的每個元素。

雖然您可以通過創建新的數據結構來更快地(理論上)創建更多內容。例如:

var hashmap = new Map();
var ArrPerson = [];
ArrPerson.push(new Person("john",12,"M1"));
hashmap.set("john",true);

這個ES6 Map將根據它包含的名稱保留整個數組的索引。如果你想查看你的數組是否包含一個名字,你可以這樣做:

hashmap.has('john')//true

這種方法將執行O(1)。只需在地圖中檢查一下,看看數組中是否存在此名稱。您還可以跟蹤地圖中的數組索引:

var index = ArrPerson.push(new Person("john",12,"M1"));
var map_indexes = hashmap.get("john");
if(map_indexes){
  map_indexes.push(index-1);
  hashmap.set("john",map_indexes);
}else{
  hashmap.set("john",[index-1]);
}
map_indexes = hashmap.get("john"); //an array containing the ArrPerson indexes of the people named john
//ArrPerson[map_indexes[0]] => a person named john
//ArrPerson[map_indexes[1]] => another person named john ...

使用這種方法,您不僅可以判斷數組中是否有具有特定名稱的人,還可以使用O(1)查找整個對象。 考慮到這個地圖只會按名稱索引人,如果你想要另一個標准你需要另一個地圖。同時保持兩個數據結構同步並不容易(從數據中刪除一個元素也應該從地圖中刪除等)

總而言之,在我們的示例中,一如既往地提高速度會犧牲其他內容,內存和代碼復雜性。

  • 使用ES5數組方法,如map,filter,reduce等
  • 使用forEach
  • 原生的循環

示例:filter,map,reduce等方法迭代數組中的每個項目或對象,

ArrPerson.filter(function(item){
       console.log(item)
   });

forEach :還迭代數組中的每個項目/對象

 ArrPerson.forEach(function(key,value){
     console.log(key);
     console.log(value)
  })

問題說大陣,所以

native for loop比上述任何一個都快,緩存長度可以提高幾毫秒(毫秒)。

https://jsperf.com/native-map-versus-array-looping

for(var i = 0, len = ArrPerson.length; i < len; i++){

}

這樣的事情應該有效。

  var Person = function(name,age,group){ this.name = name, this.age = age, this.group = group } var ArrPerson = []; ArrPerson.push(new Person("john",12,"M1")); ArrPerson.push(new Person("sam",2,"M0")); for(var key in ArrPerson){ if(ArrPerson[key].name === 'john'){ //do something alert(ArrPerson[key].name); } } 

考慮到你想要檢查所有並假設沒有其他索引,那么問題仍然是O(n)。 您可以使用.filter()過濾並返回滿足該條件的數組。 或者,您可以根據要搜索的內容使用其他一些數據結構進行索引。

 var Person = function(name, age, group) { this.name = name, this.age = age, this.group = group } var ArrPerson = []; ArrPerson.push(new Person("john", 12, "M1")); ArrPerson.push(new Person("sam", 2, "M0")); function findByName(arr, name) { return arr.filter(function(o) { return o.name == name; }); } document.write(JSON.stringify(findByName(ArrPerson, "john"))); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM