2

Javascript describes the map method syntax as:

arr.map(callback[, thisArg])

Parameters

  • callback - Function that produces an element of the new Array, taking three arguments:
  • currentValue -The current element being processed in the array.
  • index - The index of the current element being processed in the array.
  • array The array map was called upon.
  • thisArg - Value to use as this when executing callback.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

I can write a JS function that capitalizes the first letter of each word in an array of strings as follows:

capyyIt(['john', 'nelson mandela', 'james booth'])     // returns ['John', 'Nelson mandela', 'James booth']

function capyyIt(names) {
  return names.map(function capIt(curr) { return curr[0].toUpperCase() + curr.slice(1).toLowerCase(); });
}
  1. How can I write capIt with 4 parameters (even though I may not be using them all)? I'm asking because I tried it with 4 parameters but it didn't seem to work.
  2. How can I write capIt as a non-immediately invoked function expression - something like:

    function capyyIt(names) {
        return names.map(capIt);
    }
    function capIt(curr,index,arr) {
        return curr[0].toUpperCase() + curr.slice(1).toLowerCase();
    }
    
  • 1 why do you want to use 4 parameters when you only need 1 ? 2 did you try your own code? what didnt work ?Dont waste people's time unless you give them a good reason to; – mpm May 13 '14 at 04:27
  • @mpm - I'm asking because I tried it with 4 parameters but it didn't seem to work even though from the docs it seemed like it should. –  May 13 '14 at 04:57
  • __Note:__ Reminds me of my question I asked back 4 years ago: [JS callback using map() with a function that has one additional parameter](http://stackoverflow.com/questions/10872370/js-callback-using-map-with-a-function-that-has-one-additional-parameter). Though I'm not one of the guys that hit you with the [dupehammer](http://meta.stackoverflow.com/questions/tagged/dupehammer), this definitely looks damn similar... – syntaxerror Jan 29 '16 at 02:04

1 Answers1

3

I'm not entirely clear on what you're asking but lets see if this is what you're looking for:

function capyyIt(names) {
  names.map(function(value, index, collection){
     capIt(val);
  })
}   

function capIt(name) {
  return name.toUpperCase() + curr.slice(1).toLowerCase();
}

The map function takes a callback argument that uses the value, index, and collection as arguments, you can't change this. Therefore if you want to do something to each value being mapped, you should do it inside the callback function.

JoshSGman
  • 529
  • 2
  • 6
  • 16