Typescript array map vs filter vs?

Here's a typescript method that wants to loop through an array of strings and return another array of strings, where the strings that match the regex (formatted as "[la la la]" will become just "la la" la "and lines that don't match are discarded. Thus, if my input array is:

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

      

he 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 "if (match)". What's the correct typescript / javascript way to write this code?

+4


source to share


5 answers


Just filter

them:



return this.rawRecords[0].map((value) => {
        console.log(value);
        var match = regexp.exec(value);
        if (match) {
            return match[1];
        }
    });
}).filter(x=>!!x);

      

+5


source


What card is to apply your function to each item in your list. Your function does not return any value if the regex does not match. So JS is probably causing it to return undefined for these cases. If you want to remove the ones that don't match the regular expression, you should use the filter right away.



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

+1


source


I really believe that sometimes we try to make it more functional than we are. What's wrong:

var regexp = /\[(.*)\]/;
var records = this.rawRecords[0];
var res = [];

for (var i = 0, len = records.length; i < len; ++i) {
    var match = regexp.exec(records[i]);
    if (match) {
        res.push(match[1]);
    }
});

return res;

      

It's not a one-liner, and even though I don't know anything about TypeScript (you also asked about JavaScript in your question), it should also be more efficient than any functional approach.

0


source


Another option is to use the reduce () method like this:

return this.rawRecords[0].reduce((acc, value) => {
    console.log(value);
    var match = regexp.exec(value);
    if (match) {
        acc.push(match[1]);
    }
    return acc;
}, []);

      

please go to JSFIDDLE result for equivalent code in javascript.

0


source


I tried this issue out and share my result below. Hope this helps. We apologize if I am mistaken or misinterpreted as I am new to Typescript.

var arr = ["[xy]","x","y"];
var ele =[];
var i;
var op;
var regex = /\[(.*)\]/;
var op1 = arr.filter((element)=>
{
    op =regex.exec(element);
    if(op)
    ele.push(op);
    else{
        ele.push(element);
        console.log(op);
    }
    });
    for(i =0;i<ele.length;i++)
    {
        console.log(ele[i]);
    }

      

0


source







All Articles