Diane Foster Diane Foster - 9 months ago 36
Javascript Question

Check if the first letter of each element of an array is capital using filter method. But I keep getting the whole array

// JavaScript Document
"use strict";
var testArray =["beau","Diane","morgan","Brittany"];
function checkCapital(value,index,array) {
return value;
var capital =testArray.filter(checkCapital);

I need to check if the first letter of every value of the array is a capital using filter method. But I keep getting the whole array returned on my function.


Well, you are comparing an entire string with the lowercase equivalent of its first character, which is a problem. And you are going to return undefined when your condition is not satisfied, and a specific character if it is, which is a little strange. Your filter function should be

return value.charAt(0) !== value.charAt(0).toLowerCase()

or use the more modern

return value[0] !== value[0].toLowerCase()

and write the whole app in more modern JavaScript as follows:

const testArray = ["beau", "Diane", "morgan", "Brittany", "^&#SYMBOLS$$--"];
const capital = testArray.filter(s => s[0] !== s[0].toLowerCase());

but really, what is and is not an uppercase letter is an interesting problem in its own right. What if a word starts with a comma? A Cherokee or Devanagari letter? Letter-like symbols? If you really want to do uppercase properly, you might want to get a package like xregexp then you can write a filter function that matches XRegExp("^\\p{Lu}"). I understand this might be beyond what you are looking for at the moment, but it's a good thing to know about.