我想優化我的代碼CPU
和memory
消耗。在我的函數中,我需要將兩個對象數組合併到一個數組中。與UNION
一樣,數組中所有對象的所有id
都必須是唯一的。我不想使用第三方庫,如Underscore
。如何優化兩個對象數組的合併?
這是我的函數:
var presentation_slides = [
{
"id": "2",
"type": "results"
},
{
"id": "1",
"type": "slide"
},
{
"id": "4",
"type": "questions"
}]
for(var i = 0; i < new_length; i++) {
var my_slide = presentation_slides.filter(function (obj) { return obj.id == i })[0]
if(!my_slide) {
presentation_slides.push({"id": i, "type": "slide"});
}
}
OUTPUT:
var presentation_slides = [
{
"id": "2",
"type": "results"
},
{
"id": "1",
"type": "slide"
},
{
"id": "4",
"type": "questions"
},
{
"id": 0,
"type": "slide"
},
{
"id": 3,
"type": "slide"
}]
謝謝!
編輯:
比較一些測試:http://jsperf.com/how-can-be-optimized-merging-of-two-arrays-of-objects
也許一個愚蠢的問題,但什麼是數組的來源是什麼?這可以解決服務器端? –
在你的代碼中,我看到只有一個數組在其中添加新對象,也許用更準確的代碼重寫了你的問題? –