Johan
Johan

Reputation: 35194

Alter array using $.grep()

Currently, I use $.grep to filter and remove elements from the array which I pass. I believe that $.grep was intended to be used for filtering only, but since it's iterating over the entire array, I figured that I might as well alter the array inside it as well.

Do you have any other approaches that you can suggest? I had a thought about $.map, but AFAIK it should be used for translating elements, and not removing them.

Is a separate $.each my only alternative?

The relevant part of my code:

$.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;
                }

            });

        });
    }

});

Upvotes: 0

Views: 78

Answers (1)

Klas Mellbourn
Klas Mellbourn

Reputation: 44377

$.map can be used to remove items from an array, just make it return null:

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

result: [1, 3, 4]

From the documentation:

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

Upvotes: 1

Related Questions