使用$.grep()修改数组

Alter array using $.grep()

本文关键字:修改 数组 grep 使用      更新时间:2023-09-26

目前,我使用$。grep从我传递的数组中过滤和删除元素。我相信这一点。grep本来只用于过滤,但由于它要遍历整个数组,所以我认为最好也改变它内部的数组。

你能建议其他的方法吗?我有一个关于美元的想法。

单独的$.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;
                }
            });
        });
    }
});

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

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

来自文档:

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