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);