Search code examples
javascriptlodashecmascript-5

Understanding how to turn ._forEach into _.map


I'm working on a project with lodash v3. I have eslint-plugin-loadash setup to use the v3 recommendations.

Looking at the code below it recommends turning it from _.forEach into _.map. inventory.minons() is an array of objects.

      var playerArmies = [setupPlayer];
      _.forEach(inventory.minions(), function () {
        playerArmies.push(setupSubCommander);
      });

Having looked over the documentation for _.map I couldn't figure out how I'd change what I have into what it suggests. I'm less worried about whether it's the right thing to do at this point (I'm a slave to the linter due to my lack of understanding) and more just trying to expand my knowledge in the hope it will help me understand future documentation.


Solution

  • Since you have an initial value in the array, _.map won't keep that item. You'll have to use .unshift to add the item setupPlayer to the start of the array.

    var playerArmies = _.map(inventory.minions(), function () {
      return setupSubCommander;
    });
    playerArmies.unshift(setupPlayer); // adds item to the front of the array.