Question
Answer and Explanation
To extract strings from an array in JavaScript, you can use several methods. Here’s a comprehensive guide with examples:
1. Using a `for` loop:
- You can iterate through the array and check the type of each element. If it's a string, you can add it to a new array.
const myArray = [123, "Hello", 456, "World", true];
const stringArray = [];
for (let i = 0; i < myArray.length; i++) {
if (typeof myArray[i] === "string") {
stringArray.push(myArray[i]);
}
}
console.log(stringArray); // Output: ["Hello", "World"]
2. Using the `filter` method:
- The `filter` method creates a new array with all elements that pass the test implemented by the provided function. You can use `typeof` to check if an element is a string.
const myArray = [123, "Hello", 456, "World", true];
const stringArray = myArray.filter(item => typeof item === "string");
console.log(stringArray); // Output: ["Hello", "World"]
3. Using `reduce` method:
- The `reduce` method can also be used, though it's more verbose than `filter`. It executes a reducer function on each element of the array, resulting in a single output value, which in this case will be an array of strings.
const myArray = [123, "Hello", 456, "World", true];
const stringArray = myArray.reduce((acc, item) => {
if (typeof item === "string") {
acc.push(item);
}
return acc;
}, []);
console.log(stringArray); // Output: ["Hello", "World"]
4. Using `forEach` method:
- Similar to the `for` loop, the `forEach` method iterates over each element of the array. You check the type of each element and, if it is a string, push it to the new array.
const myArray = [123, "Hello", 456, "World", true];
const stringArray = [];
myArray.forEach(item => {
if (typeof item === "string") {
stringArray.push(item);
}
});
console.log(stringArray); // Output: ["Hello", "World"]
The `filter` method is usually the most concise and readable approach for extracting strings from an array in JavaScript.