使用$ .grep()更改数组

时间:2013-05-18 17:34:59

标签: javascript jquery

目前,我使用$.grep来过滤和删除我传递的数组中的元素。我相信$ .grep只是用于过滤,但由于它在整个数组上进行迭代,我想我也可以改变它内部的数组。

您有其他方法可以建议吗?我考虑过$.map,但AFAIK应该用于翻译元素,而不是删除元素。

单独的$.each是我唯一的选择吗?

我的代码的相关部分:

$.each(filter, function (k, v) {

    if (v.codeKeys) {

        $.each(v.codeKeys, function (i, codeKey) {

            rows = $.grep(rows, function (v2, i2) {

                if ($.isArray(v2[v.dbColumn]) && 
                    $.inArray(codeKey, v2[v.dbColumn]) === -1) {

                    var index = $.inArray(codeKey ,v2[v.dbColumn]);

                    if (v2[v.dbColumn][index])
                        v2[v.dbColumn].remove(index);

                    return true;

                }
                else {
                    return v2[v.dbColumn] !== codeKey;
                }

            });

        });
    }

});

1 个答案:

答案 0 :(得分:1)

$ .map可用于从数组中删除项目,只需使其返回null:

var items = [1, 2, 3, 4]
$.map(items, function(i) { if (i == 2) return null; return i; })

result: [1, 3, 4]

来自the documentation

The function can return:
    * the translated value, which will be mapped to the resulting array
    * null or undefined, to remove the item