Examples

Convert string array to integer array

I have an array of strings like [‘2′, ’10’, ’11’] and was wondering what’s the most efficient way of converting it to an integer array. Should I just loop through all the elements and convert it to an integer or is there a function that does this?

4 Answers 4

Use map() and parseInt()

var res = ['2', '10', '11'].map(function(v) < return parseInt(v, 10); >); document.write('
' + JSON.stringify(res, null, 3) + '
')

More simplified ES6 arrow function

var res = ['2', '10', '11'].map(v => parseInt(v, 10)); document.write('
' + JSON.stringify(res, null, 3) + '
')

Or using Number

var res = ['2', '10', '11'].map(Number); document.write('
' + JSON.stringify(res, null, 3) + '
')

Or adding + symbol will be much simpler idea which parse the string

var res = ['2', '10', '11'].map(v => +v ); document.write('
' + JSON.stringify(res, null, 3) + '
')

FYI : As @Reddy comment - map() will not work in older browsers either you need to implement it ( Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.) ) or simply use for loop and update the array.

Also there is some other method which is present in it's documentation please look at Polyfill , thanks to @RayonDabre for pointing out.

Источник

How do I turn an array into a number?

update: I still want to use a for loop as the section requires it and it is more simple than other methods. Hoping for the least amount of change to provide the number of the ant xxx in the string that would result after splitting, running in a for loop, and sorting by ant using startsWith. I know there are other approaches but I am looking for the simplest. I was not clear about it before but am clear about it now.

3 Answers 3

With Regexp you can accomplish that with only one line of code.

// This will return 4 matches (4 commas) + 1 = count of blocks separated by comma. new RegExp("\,", "g") 
let count = 'ant 222, bison, ant 333, ant 555, goose 234'.match(new RegExp("\,", "g")).length + 1; console.log(count);

According to your approach: Using a basic for-loop

function countAllBeasts(antMany) < var origString = antMany.split(', '); var ants = []; for (var i = 0; i < origString.length; i++) < if (origString[i].startsWith('ant')) ants.push(origString[i]); >return ants; > var beasts = 'ant 222, bison, ant 333, ant 555, goose 234'; console.log(countAllBeasts(beasts));

You can accomplish that using function filter

function countAllBeasts(antMany) < var origString = antMany.split(', '); var ants = origString.filter((block) =>block.trim().startsWith('ant')); return ants; > var beasts = 'ant 222, bison, ant 333, ant 555, goose 234'; console.log(countAllBeasts(beasts));

Источник

How to convert array of strings to array of numbers in JavaScript?

In JavaScript, there are different ways to convert an array of strings to an array of numbers. The first way is to use the built-in parseInt() method, and the second way is to use a type conversion function, and the third one is to use the unary + operator.

Using the parseInt() method

The parseInt() method is a built-in function in JavaScript that takes a string as an argument and returns a number. This method can be used to convert an array of strings to an array of numbers.

Syntax

The syntax of the parseInt() method is as follows −

Parameters

  • String − The string to be converted to a number.
  • Radix − An optional argument that specifies the base (radix) of the string. The default value is 10.

Example

The following example shows how to use the parseInt() method to convert an array of strings to an array of numbers.

     var arr = ["1", "2", "3"]; // array of strings var nums = arr.map(function(str) < // using map() to convert array of strings to numbers return parseInt(str); >); document.getElementById("result").innerHTML = nums  

In the above example, the parseInt() method is used in the map() method to convert each element in the arr array to a number. The map() method creates a new array with the results of calling a function for each element in the array.

Using a type conversion function

Another way to convert an array of strings to an array of numbers is to use a type conversion function. The type conversion function is a user-defined function that converts a data type to another data type.

Example

In the below example, a type conversion function is used to convert an array of strings to an array of numbers.

     function toNumber(value) < return Number(value); >var arr = ["1", "2", "3"]; var nums = arr.map(toNumber); document.getElementById("result").innerHTML = nums;  

In the above example, the toNumber() function converts a string to a number. This function is used to convert an array of strings to an array of numbers.

Using the unary + operator

Another way to convert an array of strings to an array of numbers is to use the unary + operator. The unary + operator is a prefix operator that converts its operand to a number.

Example

The below program shows how to use the unary + operator to convert an array of strings to an array of numbers.

      var arr = ["1", "2", "3"]; // Using the unary + operator var nums = arr.map(unaryOp); document.getElementById("result").innerHTML = nums // Function that converts string to number function unaryOp(value) 

In the above example, the unaryOp() function is a user-defined function that uses the unary + operator to convert a string to a number. This function can be used to convert an array of strings to an array of numbers.

Conclusion

In JavaScript, there are two ways to convert an array of strings to an array of numbers. The first way is to use the built-in parseInt() method, and the second way is to use a type conversion function.

Источник

How do I convert every string in split array to a number?

I have a string that needs to be split and converted into numbers. I decided to split the string and put the strings into an array and later convert them into numbers using the Array.prototype.every() function and the Number() function. When I check the type of the first array element, I see that I still have a string and not a number. Where is my mistake? The answer here makes it look like after splitting JS would convert to number automatically but that isn't happening as evidenced by logging the type of the first element.

function detectOutlierValue(string) < // convert string into array with numbers, 'separator " " var numArray = string.split(' '); console.log(typeof numArray[0]); console.log(numArray); numArray.every(function (item) < return Number(item); >); console.log(numArray, typeof numArray[0]); 
string [ '2', '4', '7', '8', '10' ] [ '2', '4', '7', '8', '10' ] 'string' 

1. you are doing mistake in splitting. 2. every() is not used like this. 3. you need to use parseInt() to convert string to numbers!

4 Answers 4

You've got your array methods confused. Array.prototype.every is used to determine if every element in an array satisfies a certain condition specified by the callback. Basically, your code is converting every element to a number and then to a boolean for every , and every will return a boolean if the callback returns true for every element it's called on.

Instead, you are looking for Array.prototype.map which performs a function on each element, mapping them to a new value:

var splitString = string.split(' '); var numArray = splitString.map(Number); 

This will map the Number constructor (which is the callback) to every element converting it to a number. Note that numArray holds the transformed array, but splitString still contains the array of strings. Number will return NaN if the string is not numeric.

Источник

Читайте также:  Python install windows terminal
Оцените статью