Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript array map vs filter vs?

Here's a typescript method that wants to walk through an array of strings, and return another array of strings, where, strings that match the regexp (formatted something like "[la la la]" will become just "la la la" and strings that don't match are dropped. So that if my input array is:

"[x]", "x", "[y]"

it becomes

"x", "y"

Here's my code:

questions(): string[] {
    var regexp = /\[(.*)\]/;
    return this.rawRecords[0].map((value) => {
        console.log(value);
        var match = regexp.exec(value);
        if (match) {
            return match[1];
        }
    });
}

I end up with output like this:

"x", undefined, "y"

because of the "if (match)". What's the right typescript/javascript way of writing this code?

like image 528
pitosalas Avatar asked Jul 02 '15 01:07

pitosalas


2 Answers

Just filter them out:

return this.rawRecords[0].map((value) => {
        console.log(value);
        var match = regexp.exec(value);
        if (match) {
            return match[1];
        }
    });
}).filter(x=>!!x);
like image 86
basarat Avatar answered Sep 28 '22 19:09

basarat


What map does is to apply your function to each and every element in your list. Your function does not return any value when regex is not matched. So, probably JS makes it return undefined for that cases. If you wanna drop the ones that do not match regexp, you should use filter right away.

Think about names of functions and you will have a better understanding right away(map maps a function to a list and filter filters a list).

like image 39
codanza Avatar answered Sep 28 '22 19:09

codanza