Fez Vrasta
Fez Vrasta

Reputation: 14815

$.map and $.grep together?

I have this simple script:

var stdout = "A test.js\nD README.md\nD CONTRIBUTING.md\nM something.txt";

var out = $.grep( stdout.split("\n"), function (row) {
    return (row.substring(0, 1) == "D");
});

JSFIddle [x]

It returns an array with only the rows starting with D, this is the result:

D README.md
D CONTRIBUTING.md

I need to get, instead, an array with the rows starting with D but I need to strip the D from the rows, so I would need this result:

README.md
CONTRIBUTING.md

If I use only $.map I can't find a way to don't return anything in case the condition is not fulfilled...

var out = stdout.split("\n").map(function (row) {
    return (row.substring(0, 1) == "D") ? row.substring(1).trim() : null;
});
// returns: [null, 'README.md', 'CONTRIBUTING.md', null]
// I need: ['README.md', 'CONTRIBUTING.md']

I think I should use a mix of $.map and $.grep but looks like too much code for this simple task.
What is the best way to achieve this?

Upvotes: 0

Views: 100

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You can just use $.map() - if you return undefined from $.map() callback, that value will be ignored

var regex = /^D/;
var out = $.map(stdout.split("\n"), function (row) {
    return regex.test(row) ? $.trim(row.substring(1)) : undefined
});

Demo: Fiddle

Upvotes: 3

Related Questions