I have a set of div elements:
<div class="myDiv" key="default">Default Val</div>
<div class="myDiv" key="default">Default Val2</div>
<div class="myDiv" key="myVal-1">Value 1</div>
<div class="myDiv" key="myVal-2">Value 2</div>
<div class="myDiv" key="myVal-3">Value 3</div>
And I want to collect all 'key' attributes except those with 'default' value into an array. I know I can use _.each() for that, but is there a lodash function that is a combination of _.map() and _.filter()? In other words I need something like this:
arr = _.func($('.myDiv'), (el) => {
// collects truthy values and ignores falsy ones
return $(el).attr('key') == 'default' ? $(el).attr('key') : false;
});
arr // => ["myVal-1", "myVal-2", "myVal-3"]
There is reduce where you can define anything in a loop. But it doesn't necessarily mean it's easier to read.
arr = _.reduce($('.myDiv'), (result, el) => { const key = $(el).attr('key'); if (key !== 'default') result.push(key); return result; }, []);Just use map and filter :
arr = _.filter( _.map( $('.myDiv'), el => $(el).attr('key') ), key => key != 'default' );