Reputation:
// 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 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.
Upvotes: 0
Views: 1624
Reputation: 11
solution :-
function checkUppercase(arr)
{
var array1 = arr.split(' ');
var newarray1 = [];
for(var x = 0; x < array1.length; x++){
newarray1.push(array1[x].charAt(0).toUpperCase()+array1[x].slice(1));
}
newarray1.join(' ');
let i=0;
if(JSON.stringify(array1) == JSON.stringify(newarray1)) {
return true
}else {
return false;
}
}
console.log(checkUppercase("solid Is Transparent"));
Upvotes: 0
Reputation: 88378
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.
Upvotes: 1
Reputation: 16033
First off you are always returning value
from your filter function, that is the core reason why you are getting the whole array. A filter function shold return true or false depending on whether the value should or should not be included in the output.
You have other issues with your code but try and solve them on your own.
Upvotes: 0
Reputation: 3780
The filter()
method depends on the return
statement of the callback, which if returns true
then filter()
will include the current value to the array it will return. Just remove your if
statement and put the condition on the return
statement:
function checkCapital(value,index,array) {
return value !== value.charAt(0).toLowerCase();
}
Because your original callback returns true
always, it would include all elements of the original array to be returned by the filter()
method.
Upvotes: 0