Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i separate number and string from an Array collection in JavaScript?

I am learning JavaScript, I want to separate number and string from an Array collection. I can’t do this. Can anyone help me how can i do this?

Here is my code example:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];

I want like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1, 3, 5]
['abc', 'def', 'ghi']

How can i do this?

>Solution :

You can do this with JavaScript built-in array.filter() method.

Here is the solution:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];

const numbers = array.filter((item) => typeof item === "number");
const strings = array.filter((item) => typeof item === "string");

console.log(numbers); // [1, 3, 5]
console.log(strings); // ['abc', 'def', 'ghi']

I think it will solve your problem.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading