Separating Numbers and Non-Numbers in JavaScript
How can we separate an array of strings into two arrays of numbers and non-numbers using JavaScript?
Given an array of strings, some containing valid numbers and others not, how can we categorize them into two separate arrays?
Solution:
To separate an array of strings into two arrays, numbers and non-numbers, a JavaScript function which checks each item can be created. If the item is a valid number, it is added to the 'numbers' array, otherwise it is placed in the 'non-numbers' array. The function then returns a JSON object containing both arrays.
To solve this problem, we can utilize JavaScript. The goal is to separate the array into two arrays and post them in a JSON object. One will contain the valid numbers labeled as "numbers" and the other will contain all other strings labeled as "non-numbers."
Here is a simple JavaScript function that achieves this:
function separateStrings(inputArr) {let numbers = [];
let nonNumbers = [];
for (let i = 0; i < inputArr.length; i++) {
if (!isNaN(inputArr[i])) {
numbers.push(parseFloat(inputArr[i]));
} else {
nonNumbers.push(inputArr[i]);
}
}
return { 'numbers': numbers, 'non-numbers': nonNumbers };
}
The function works by iterating through each item in the input array. If the item is a valid number (checked using the isNaN function), it is parsed to a floating-point number (to accommodate decimal numbers) and added to the 'numbers' array. If the item is not a number, it is added to the 'non-numbers' array. The function finally returns a JSON object containing the two arrays.
By using this function, we can efficiently categorize strings into numbers and non-numbers in JavaScript.