We will explain a function to which we send the array and convert all its contents to lowercase letters
const toLowerCaseArray = (array) => {
if (!Array.isArray(array)) {
throw new Error('Input must be an array');
}
return array.map(item => {
if (typeof item === 'string') {
return item.toLowerCase();
}
return item; // Return the item unchanged if it's not a string
});
};
var array1 = ['Hello', 'WORLD', 'JavaScript'];
var lowerCaseArray1 = toLowerCaseArray(array1);
console.log(lowerCaseArray1);
Yes, as you can see, it is just a function. Send in the array parameter. Then the function converts all its elements into to Lower Case for words.
But we hope we don't build something much stronger
*We want to build something that uses JavaScript connectivity
*
var array1 = ['Hello', 'WORLD', 'JavaScript'];
var lowerCaseArray1 = array1.toLowerCaseArray();
console.log(lowerCaseArray1);
NOT
var array1 = ['Hello', 'WORLD', 'JavaScript'];
var lowerCaseArray1 = toLowerCaseArray(array1);
console.log(lowerCaseArray1);
Our code will be
Array.prototype.toLowerCaseArray = function() {
if (!this.every(item => typeof item === 'string')) {
throw new Error('All elements in the array must be strings');
}
return this.map(item => item.toLowerCase());
};
var array1 = ['Hello', 'WORLD', 'JavaScript'];
var lowerCaseArray1 = array1.toLowerCaseArray();
console.log(lowerCaseArray1);
Top comments (0)