I have an array as follows:
var array = ['Bob','F', 'Nichols'];
I want to detect whether this array contains any values that are a single character long. In other words, I want to know whether there are any initials in this person's name.
var array = ['Bob','F', 'Nichols']; //true
var array = ['B','Freddy', 'Nichols']; //true
var array = ['Bob','Freddy', 'N']; //true
var array = ['B','F', 'N']; //true
var array = ['B','F', 'N']; //true
var array = ['Bob','Freddy', 'Nichols']; //false
if (anyInitials(array)) {
console.log("there are initials");
} else {
console.log("there are no initials");
}
function anyInitials(a) {
var arrayLength = a.length;
var initial = 'no';
for (var i = 0; i < arrayLength; i++) {
if (a[i].length == 1){
initial = 'yes';
}
}
return initial;
}
You can use the function some
let array = ['Bob','F', 'Nichols']; console.log(array.some(({length}) => length === 1));
let anyInitials = a => a.some(({length}) => length === 1) ? "yes" : "no";
You can use a simple .forEach()
loop like below. This loops through the array, and sets isInitial
to true if the length is 1.
var array = ['Bob', 'F', 'Nichols']; function anyInitials(a) { var isInitial = false; a.forEach(e => { if (e.length == 1) { isInitial = true; } }); return isInitial; } console.log(anyInitials(array));
You can also use .some()
like below. This will return true if any element in the array has a length of 1.
var array = ['Bob', 'F', 'Nichols']; function anyInitials(a) { return array.some(e => e.length == 1); } console.log(anyInitials(array));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.