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:
[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.