user3911545
user3911545

Reputation: 309

Change starting position in lodash map()

I need to map an array starting from index 1, not 0. How can I do this using map()? Here's what I have so far:

function getStoryCard(value, key) {
    return {
        imageSection: storyCardMedia[OVERVIEW_DRAWERS_CONSTANTS.STORYCARD + key],
        linkOut: value.Link || null,
        subTitle: value.Subtitle || null,
        title: value.Title || null,
        viewMore: value.ViewMore ? getViewMore(value.ViewMore) : null,
        type: storyCardType
    }
}

// This method gets an object array
// [Object, Object....]
storyCards = _.map(pickedCards, getStoryCard);

// Set index to 1, but map method already has executed
for (var i = 1; i <= storyCards.length; i++) {

    if (storyCards.imageSection === undefined) {
        storyCards.splice(0, 1);
    }

    storyCards[i];
}

return storyCards;

Upvotes: 1

Views: 869

Answers (3)

Adam Boduch
Adam Boduch

Reputation: 11211

Why not use rest()?

storyCards = _.map(_.rest(pickedCards), getStoryCard);

Upvotes: 2

arjabbar
arjabbar

Reputation: 6404

Use the slice function that's on arrays before calling map.

Off the top of my head I believe

arr.slice(1)

will give you the array minus the first entry.

Upvotes: 2

Ryan Miller
Ryan Miller

Reputation: 1053

_.map is passing you the index - it only provides keys when you pass in an object, and since you're passing in an array, you're solid.

However, unlike filter, map always inserts a value into the returned array, even if that value is something like undefined (if you decide to return at index 0). Thus, you'd end up with something like [undefined, {}, {}, {}]. Not good.

One way you could solve this would be to use another lodash method, compact. Compact simply iterates through an array removes falsey values. Your above code sample would then become:

function getStoryCard(value, index) {
    imageSection = storyCardMedia[OVERVIEW_DRAWERS_CONSTANTS.STORYCARD + index];

    if (!imageSection || index === 0) return;       

    return {
        imageSection: imageSection,
        linkOut: value.Link || null,
        subTitle: value.Subtitle || null,
        title: value.Title || null,
        viewMore: value.ViewMore ? getViewMore(value.ViewMore) : null,
        type: storyCardType
    }
}

return _.compact(_.map(pickedCards, getStoryCard));

We iterate through pickedCards, accepting those cards we wish to. Those cards we don't want to insert simply become undefined in the array, which compact will subsequently remove. Hope this helps!

Upvotes: 1

Related Questions