2013-07-15 80 views
3

我有一個數組,其中包含任意數量的subarrays,每個數組都包含兩個值。子陣列具有特定值時刪除數組元素

i.e: interestArray[[1, 5], [3, 8] ... ] 

如何刪除包含值[3,8]的subarray

我的代碼是:

$('td', container).click(function(){ 
     if(!$(this).hasClass('purchased') && !$(this).hasClass('manu')) 
     { 
     var manuId = $(this).parent().children('td:first-child').data('manu-id'); 
     var typeId = $(this).data('type-id'); 
     if($(this).hasClass('interest')) 
     { 
      $(this).removeClass('interest'); 
      $(this).parent().children('td.manu').removeClass('interest'); 
      var index = interestArray.indexOf([manuId, typeId]); 
      interestArray.splice(index, 1); 
     } else { 
      $(this).addClass('interest'); 
      $(this).parent().children('td.manu').addClass('interest'); 

      interestArray.push([manuId, typeId]); 
     } 
     //updateSurvey(interestsArray); 
     console.log(interestArray) 
     } 
    }) 

下段不工作,並簡單地刪除第一個subarray

var index = interestArray.indexOf([manuId, typeId]); 
interestArray.splice(index, 1); 
+0

[對比兩個數組可能重複在Javascript](http://stackoverflow.com/questions/7837456/comparing-two-arrays-in-javascript) – RoToRa

+0

比較不過濾/刪除元素。 – imperium2335

+0

不,但您的主要問題是確定要刪除的項目。一旦你找到了它,刪除它變得微不足道。 – RoToRa

回答

2

這裏是符合你的要求的一般做法:

var arr = [[1,2],[3,4],[5,6]]; 
var remove = [3,4]; 

for (var i=0; i<arr.length; i++) { 
    if (arr[i][0] == remove[0] && arr[i][1] == remove[1]) { 
    arr.splice(i, 1); 
    break; 
    } 
} 

console.log(arr); //=> [[1,2],[5,6]] 
+0

當您找到匹配時,您可能需要「休息」;否則向後循環,以防萬一有多個匹配的可能性 – Ian

+0

這將跳過第二個連續匹配。 (因此,如果以'var arr = [[1,2],[3,4],[3,4],[5,6]];'開頭,則末尾的輸出將爲[[1, 2],[3,4],[5,6]](第二個「[3,4]」仍在列表中)。 –

1

對於一般的方法,您可以filter數組:

var reducedArray = interestArray.filter(function (item) { 
    return item[0] != manuId || item[1] != typeId; 
}); 

不能使用indexOf因爲看起來對同一對象(不只是一個等效之一)。

如果您正在運行的JS的早期版本沒有Array.filter,那麼在鏈接到上面的filter文檔頁上有一個很好的補充。

0

這是我個人的解決方案更加完整,避免多次入境問題和突破;上面看到的東西,這也避免了一個問題,如果陣列是項刪除後(這是基於jQuery的,但你可以做一個定期循環,如果你感覺更舒服吧):

$.each(answers, function(index, value){ 
     if (typeof answers[index] != "undefined") 
     { 
      if(answers[index]["question_id"]==answer_to_del) 
      { 
       delete answers[index]; 
      } 
     } 

    }); 
    //Clean answer array from empty values created above 
    answers = answers.filter(function(n){ return n != undefined });