2

I'm trying to write a function that will capitalize the first letter of the first and last name only... any ideas on how to approach this?

const namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];

function capitalizeNames(peopleArray) {
    return peopleArray.toString().toLowerCase().split('').map(function(word) {
        return (word.charAt(0).toUpperCase() + word.slice(1));
    }).join(' ').split();
}


// set the resulting array to this variabble
const capitalizedNames = capitalizeNames(namesHardest);
capitalizedNames;
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
user8227859
  • 65
  • 1
  • 8
  • can you see what `.split('')` does? i.e. not what you want – Jaromanda X May 07 '18 at 22:55
  • @JaromandaX I think the problem is even before that with the toString(), no? I just don't know what I could use instead. – user8227859 May 07 '18 at 22:56
  • nope, array.toString will give you the incoming array as one string, separated by spaces - though, probably not what you want either - you need to work on each element of the array separately – Jaromanda X May 07 '18 at 22:57
  • 3
    something like `return peopleArray.map(name => name.split(' ').map(word => word[0].toUpperCase() + word.slice(1).toLowerCase()).join(' '))` – Jaromanda X May 07 '18 at 22:59
  • something _exactly_ like that. – Stephen P May 07 '18 at 23:01
  • I wasn't sure :p – Jaromanda X May 07 '18 at 23:02
  • @JaromandaX that works perfectly - thank you!! – user8227859 May 07 '18 at 23:02
  • Is this always English? It's not always just the first letter in other languages. – loganfsmyth May 07 '18 at 23:10
  • @loganfsmyth This isn't even always correct for English. I know someone with the last name `dell'Erba` so this would take his _properly_ capitalized name and make it wrong. See [Falsehoods Programmers Believe About Names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) – Stephen P May 07 '18 at 23:35
  • @StephenP True! – loganfsmyth May 08 '18 at 00:09
  • Does this answer your question? [Trying to capitalize the first character in array of strings, why this is not working?](https://stackoverflow.com/questions/7743582/trying-to-capitalize-the-first-character-in-array-of-strings-why-this-is-not-wo) – NAND Aug 07 '20 at 09:03

4 Answers4

7

One issue is using array.toString - that results in a string like

'emIly sMith angeliNA Jolie braD piTt'

so, you've lost your array elements

You need to work on each element individually, by using array.map

function capitalizeNames(peopleArray) {
    return peopleArray.map(function(name) { 
        /* do something with each name * 
    })
}

Your other issue is that split('') splits a string into characters - but you want to split it on spaces ... i.e. split(' ')

So now, we have

function capitalizeNames(peopleArray) {
    return peopleArray.map(function(name) { 
        return name.split(' ').map(function(word) { 
            /* do something with each part of name * 
        });
    });
}

so, now, how to capitalise a string - your code works, but I prefer

word[0].toUpperCase() + word.slice(1).toLowerCase();

put it together and you get

function capitalizeNames(peopleArray) {
    return peopleArray.map(function(name) { 
        return name.split(' ').map(function(word) { 
            return word[0].toUpperCase() + word.slice(1).toLowerCase();
        });
    });
}

or, in ES2015+, using arrow functions (since your code uses const, why not use all of ES2015+)

const namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];

const capitalizeNames = peopleArray => peopleArray.map(name => 
 name.split(' ').map(word => 
  word[0].toUpperCase() + word.slice(1).toLowerCase()
 ).join(' ')
);

const capitalizedNames = capitalizeNames(namesHardest);
console.log(capitalizedNames);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • This is something I need to learn, writing comprehensive answer :) – sumit May 07 '18 at 23:27
  • 1
    I do it so rarely :p usually only when the question shows an honest attempt :p I like your answer, by the way, just goes to show there's always several ways to skin a cat in JS :p – Jaromanda X May 07 '18 at 23:28
3

Sorry I am late to party, I'd rather use array.from with closure

const namesHardest = ['emIly jack sMith', 'angeliNA Jolie', 'braD piTt'];
let conv=Array.from(namesHardest,a=>a.toLowerCase().replace(/\b[a-z]/g, function(letter) {
    return letter.toUpperCase();
}))
console.log(conv);
sumit
  • 15,003
  • 12
  • 69
  • 110
0

let namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];

namesHardest = namesHardest.map(val => {
   let [first, last] = val.toLowerCase().split(' ');
   first = first.replace(first[0], first[0].toUpperCase());
   last = last.replace(last[0], last[0].toUpperCase());
     return `${first} ${last}`
});

console.log(namesHardest);
Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60
0

Your logic is a bit off. First, for each string, you need to split it by spaces to get the first and last name. Then, you can upcase the first character of each string. See below:

const namesHardest = ['emIly sMith', 'angeliNA Jolie', 'braD piTt'];

const capitalizeName = (name) => `${name[0].toUpperCase()}${name.slice(1)}`;

const capitalizeNames = (peopleArray) => peopleArray.map(name => {
  const [first, last] = name.toLowerCase().split(' ');
  return `${capitalizeName(first)} ${capitalizeName(last)}`;
});

console.log(capitalizeNames(namesHardest))
AnilRedshift
  • 7,937
  • 7
  • 35
  • 59