从2D阵列中删除多个数组

时间:2014-07-15 17:09:15

标签: javascript jquery multidimensional-array

我的网络应用程序正在接收任意大的2D数组,有时看起来像这样:

var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];

我想编写一个函数来取出multiArray中完全由引号组成的每个数组。换句话说,任何看起来像这样的数组:

["","","",""]

应该从multiArray中删除。

我尝试编写以下函数,但在for循环中使用splice的问题是拼接会改变数组的长度,最后我试图访问未定义的元素。请帮忙!

谢谢!

这是我写的错误功能:

function cleanWhitespace(arrayOfArrays) {
    var i;
    var arrayOfArraysLength = arrayOfArrays.length;
    for (i = 0; i < arrayOfArraysLength; i++) {
        var cleanedArray = $.grep(arrayOfArrays[i], function(element) {
                                return element != ""
                            });
        if (cleanedArray.length == 0)  {
            arrayOfArrays.splice(i, 1);
        }
    }
    return arrayOfArrays;
};

5 个答案:

答案 0 :(得分:4)

您可以使用$.grep

multiArray = $.grep(multiArray, function(v){
    return v.join('');
});

小提琴:http://jsfiddle.net/scZcB/

答案 1 :(得分:1)

动态:

var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];
var outputArr = removeQuoteArrays(multiArray);
console.log(outputArr);

function removeQuoteArrays(arr) {
    var outputArr = [];

    for (var i = 0; i < arr.length; i++) {
        var currArr = arr[i];
        var isAllQuotes = true;
        for (var j = 0; j < currArr.length; j++) {
            if (currArr[j] != "") {
                isAllQuotes = false;
                break;
            }
        }

        if (!isAllQuotes) {
            outputArr.push(currArr);
        }
    }
    return outputArr;
}

这里是JSFiddle

答案 2 :(得分:1)

改为创建一个新数组。

// Only add if...
cleanedArray = multiArray.filter(function(arr){
    // Some elements are not blank
    return arr.some(function(e){ return e !== "" }) 
})

答案 3 :(得分:0)

我为你的函数添加了一个长度检查,以便在索引达到数组长度时突破循环:

if (i >= arrayOfArrays.length)
      break;

这使得:

function cleanWhitespace(arrayOfArrays) {
    var i;
    var arrayOfArraysLength = arrayOfArrays.length;
    for (i = 0; i < arrayOfArraysLength; i++) {
        var cleanedArray = $.grep(arrayOfArrays[i], function(element) {
                                return element != ""
                            });
        if (cleanedArray.length == 0)  {
            arrayOfArrays.splice(i, 1);
            if (i >= arrayOfArrays.length)
                break;
        }
    }
    return arrayOfArrays;
};

答案 4 :(得分:0)

var multiArray = [["","","",""],[1,2,3],["hello","dog","cat"],["","","",""]];

function cleanWhitespace(arrayOfArrays) {
    for (var i = 0; i < arrayOfArrays.length; i++) {
        var emptyElements = 0;

        for (var j = 0; j < arrayOfArrays[i].length; j++ ) {
            if (arrayOfArrays[i][j] === "") {
                emptyElements++;
            }
        }

        if (emptyElements === arrayOfArrays[i].length) {
            arrayOfArrays.splice(i, 1);
        }
    }

    return arrayOfArrays;
}

console.log(cleanWhitespace(multiArray));

http://jsfiddle.net/4Jfr9/