Home > other >  How to print only strings from an array containing different data types in JavaScript
How to print only strings from an array containing different data types in JavaScript

Time:01-03

I have:

const fruits = ["Banana", "Orange", "Apple", "Mango", 9];
let text = fruits.toString();
console.log(text)

It prints the entire array but I only want to print the string elements of the array and exclude 9, how can I do that?

Result - Banana, Orange, Apple, Mango, 9

Desired result - Banana, Orange, Apple, Mango

CodePudding user response:

Use array filter and typeof to get the results

const fruits = ["Banana", "Orange", "Apple", "Mango", 9];

let text = fruits.filter(r => typeof(r) === "string");

console.log(text)

CodePudding user response:

const fruits = ["Banana", "Orange", "Apple", "Mango",9];
let text = fruits.filter(f => typeof (f) === 'string').toString();
console.log(text)

The typeof operator can be used to determine the data type of each object.

The filter can be used to filter out only those elements that satisfies the given condition or predicate.

CodePudding user response:

const fruits = ["Banana", "Orange", "Apple", "Mango", 9]
.filter(text => typeof(text) === "string").toString();
    
    console.log(fruits)

CodePudding user response:

Simply filter the items (using the filter function) whose type is a string (using typeof operator).

const fruits = ["Banana", "Orange", "Apple", "Mango",9];
// filter the string data type items
let text = fruits.filter(item => typeof item === "string").toString();
console.log(text)
  • Related