deferred.map: return nothing in some iteration

238 views
Skip to first unread message

Bitliner

unread,
May 11, 2013, 10:45:55 PM5/11/13
to defer...@googlegroups.com
I execute a map on an array.
I want to return only some (transformed) values of this array, only those that satisfies a condition.
But if i return only when condition is satisfied the result will contain undefined values.
Is there a way to return only some values?

deferred.map(item, function(item){
        if (item=='string'){
            return ngram
        }
}).then(function(res){
            // res is [undefined,'string',undefined] - I would like it as ['string']
})

Mariusz Nowak

unread,
May 12, 2013, 10:15:20 AM5/12/13
to defer...@googlegroups.com
@Bitliner you should just fallback to regular `filter` for arrays.

You can do it either via invoke

deferred.map(item, function () { ...}).invoke('filter', Boolean).then(function (res) {
  // res is ['string'];
});

or (as it's sync operation) you can just filter your result directly when you have it:

deferred.map(item, function () { ...}).then(function (res) {
  res = res.filter(Boolean);
  // res is ['string'];
});

Mind that `Boolean` will filter all falsy values (so also empty strings and 0 etc.) if you want to filter just undefined and null, use `function (val) { return val != null; }` instead.

Hope that helps.

Giovanni Gaglione

unread,
May 12, 2013, 11:00:13 AM5/12/13
to defer...@googlegroups.com
Thanks. I already used filtering, I  was imagining a map function that automatically rejects all values that is not returned.

 


2013/5/12 Mariusz Nowak <mar...@medikoo.com>

--
You received this message because you are subscribed to a topic in the Google Groups "deferred-js" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/deferred-js/tesRxkMBxAY/unsubscribe?hl=en.
To unsubscribe from this group and all its topics, send an email to deferred-js...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
Giovanni Gaglione                           

Telefono: +39 388 - 75.06.756
Email: giovanni...@gmail.com
Skype: bitliner 

Mariusz Nowak

unread,
May 12, 2013, 11:19:53 AM5/12/13
to defer...@googlegroups.com
Map is map, there's no filtering involved, and composability is much better when map and filter are separate functions.
Reply all
Reply to author
Forward
0 new messages