2014-11-08 62 views
2

我有一個數組,我用範圍滑塊過濾。如果特定選定參數的值在用戶設置的最小值(tMin)和最大值(tMax)值內,則將其添加到新數組(myNewArray)中,並以我需要的方式重新格式化它。超出範圍的任何內容都不會添加到此新陣列中。這部分工作得很好。範圍過濾和拼接陣列

我似乎無法工作的事情是我有一個單獨的數組(myOtherArray)格式與myArray完全一樣,但不是重新格式化它,我只需要刪除行,如果它不掉在範圍之內。 myOtherArray應該與myNewArray具有相同的值和行數,但它們的格式不同。我在這裏做錯了什麼?

myArray.map(function (dataPoint, index) { 
    if (index > 0) { 
     dataPoint.map(function (value, column) { 
      // this first part works fine 
      if (dataPoint[paramToFilter] >= tMin && dataPoint[paramToFilter] <= tMax) { 
       myNewArray[column] ? myNewArray[column].push(+value) : myNewArray[column] = [+value] 
      } 
      // this is what I cannot get to work 
      if (dataPoint[paramToFilter] < tMin || dataPoint[paramToFilter] > tMax) { 
       myOtherArray.splice(index, 1); 
      } 

     }) 
    } 
}) 

謝謝!!

+0

爲什麼你使用'Array.map'也不回什麼? – adeneo 2014-11-08 16:10:31

+0

顯然他不知道'Array.forEach'。 – Barmar 2014-11-08 16:11:44

+0

@Barmar - 或者他可以返回true或false來映射出一個新的數組,而不是在循環中使用push,splice和whatnot? – adeneo 2014-11-08 16:14:07

回答

2

的問題是,myOtherArray值是不相同的索引中myArray一旦你叫myOtherArray.splice(index, 1)

下面是該問題的一個小例子:http://jsbin.com/wipozu/1/edit?js,console

爲了避免這個問題,你可能被刪除,而不是立即刪除它的簡單的「標記」的數組項。當您完成所有檢查時(在myArray.map(...)之後),您可以刪除所有「已標記」的項目。

所以不是叫你myOtherArray.splice(index, 1);更換undefined的項目(或任何其他值) - >myOtherArray[index] = undefined; ,又重新運行以下以刪除所有這些undefined項目。

​​

同樣的例子,從之前但是使用我的解決方案:http://jsbin.com/wipozu/2/edit?js,console

所以,你的代碼看起來是這樣,那麼:

myArray.map(function (dataPoint, index) { 
    if (index > 0) { 
     dataPoint.map(function (value, column) { 
      if (dataPoint[paramToFilter] >= tMin && dataPoint[paramToFilter] <= tMax) { 
       myNewArray[column] ? myNewArray[column].push(+value) : myNewArray[column] = [+value] 
      } 

      if (dataPoint[paramToFilter] < tMin || dataPoint[paramToFilter] > tMax) { 
       myOtherArray[index] = undefined; // should be removed afterwards 
      } 

     }) 
    } 
}) 

// remove all items that have been marked 
for (var i = 0; i < myOtherArray.length; i++) 
{ 
    if (myOtherArray[i] === undefined) 
    { 
     myOtherArray.splice(i, 1); 
     // correct the index to start again on the same position because all 
     // followings item has moved one index to the left in the array 
     i--; 
    } 
} 
+0

非常感謝你,這就像一個魅力! – 8imon 2014-11-08 20:19:07

0

問題是,當拼接出一個元素時,所有下列元素的索引向下移動。因此,myArraymyOtherArray中的索引不再同步,並且在稍後執行myOtherArray.splice(index, 1)時,將刪除錯誤的元素。

最簡單的辦法是迭代從高分到低分,而不是從低到高:

for (var index = myArray.length-1; index > 0; index--) { 
    ... 
}