Diane Foster Diane Foster - 1 month ago 5
Javascript Question

I need to check if value is in first letter is a capital with filter method.Keep getting the whole array returned

// JavaScript Document
"use strict";
var testArray =["beau","Diane","morgan","Brittany"];
function checkCapital(value,index,array) {
if(value!==value.charAt(0).toLowerCase())
return value;
}
var capital =testArray.filter(checkCapital);
console.log(capital);


I need to check if value is in first letter is a capital with filter method.Keep getting the whole array returned.

Answer

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());
console.log(capital);

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.