Background information: I have an array
this.someArray = ["Word", "123", "456"]
Where this.someArray is dynamically written (the array elements are not hardcoded)
I need to convert all items that are numbers into numbers (yes I realise that this might not make sense, essentially this is the result I want - where the numbers don't have quotes but leave the words as they are):
["Word", 123, 456]
So the steps I've thought in terms of how to achieve this:
To achieve this I have:
isNumber(number) {
return !isNaN(parseFloat(number)) && !isNaN(number-0)
}
Use a for each loop to test whether each element is a word or number
this.someArray.forEach(element => { this.isNumber(element) });
Write an if statement (if the element in this.someArray is a number then remove the quotes from that element)
However I'm unsure of whether step 2 is actually the correct thing to do and I'm unsure of how to write step 3
Is there a way to accomplish this?
Further info:
This is what the dynamically generated array looks like:
This is the code:
this.someArray = this.biggerArray.map((n) => {
const data = [];
for (var key of Object.keys(n)) {
data.push(n[key].data);
}
return data;
});
I think a plain .map
would be easier - check if the string is composed of all digits with a regular expression, and if so, call Number
on it:
const arr = ["Word", "123", "456"]; const newArr = arr.map( str => /^\\d+$/.test(str) ? Number(str) : str ); console.log(newArr);
^\\d+$
means:
^
- start of string \\d+
- one or more digits $
- end of string If the numbers might contain decimals, then add an optional group for the decimal portion:
const arr = ["Word", "123", "456", '12.45']; const newArr = arr.map( str => /^\\d+(?:\\.\\d+)?$/.test(str) ? Number(str) : str ); console.log(newArr);
For the array of ['Process', '1287']
, it still works as expected:
const arr = ['Process', '1287']; const newArr = arr.map( str => /^\\d+(?:\\.\\d+)?$/.test(str) ? Number(str) : str ); console.log(newArr);
This approach also works for decimals within quotes.
for (let i in someArray) {
if (parseFloat(someArray[i])) {
someArray[i] = parseFloat(someArray[i]);
}
}
This is a shorter way of doing it.
for (let i in someArray) {
parseFloat(someArray[i]) && (someArray[i] = parseFloat(someArray[i]));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.