ParseInt elements in array to int - javascript

Suppose you have an array of the following element basically three numbers: 2,000 3,000, and 1,000
In order to say multiply each by 1,000 you would have to parse it to be set as an int:
var i = 0;
var array_nums[3,000, 2,000, 1,000];
for(i = 0; i < array_nums.length; i++){
array_nums[i] = parseInt(array_nums[i]);
}
arraytd_dth_1[i]*1000;
//arraytd_dth_1[i].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Once parsed I would want to multiply by them by 1,000 and display them so that it has commas for every three digits. This is just a general solution I came up with for Javascript and JQuery.

2,000 is not a number. It's a String.
You should first remove the commas and then parse it to a number.
var i = 0;
var array_nums = ["3,000", "2,000", "1,000"];
for (i = 0; i < array_nums.length; i++) {
array_nums[i] = parseInt(array_nums[i].replace(new RegExp(",", 'g'), "")) * 1000;
}
console.log(array_nums);

You can do it in a forEach and use toLocaleString() to format with commas. Straight Javascript ... no JQuery necessary.
var array_output=[];
var array_nums = [3000, 2000, 1000];
array_nums.forEach(x => {
array_output.push((x*1000).toLocaleString());
})

if you are using ES6 try let newArr = array_nums.map(data => data*1000)

Related

How to add sum of currency values of an array in javascript

how to add currency values of an array like this
array = [ '$0',
'$0',
'$14,792',
'$152,445',
'$1,581,033',
'$2,988,978',
'$4,226,419',
'$7,254,960',
'$10,726,945',
'$12,657,402',
'$35,215,787',
'$37,968,368',
'$7,648,445',
'$364,237',
'$390,395',
'$306,080',
'$3,641,253',
'$4,328,363',
'$1,360,664' ]
here is my method defined, the only problem i am facing is in the second for array_sum is not adding the values that i am getting from data variable.
exports.GetMonthsFWSeasonFullSeasonValues = () => {
var promises = [];
var array_sum = 0;
for(var month_index = 9; month_index <= 27 ; month_index++){
const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, month_index);
promises.push(element(by.xpath(elm_xpath)).getText());
}
return Promise.all(promises).then(function(data){
if(data != null) {
for (var array_index = 0; array_index < data.length; array_index++){
array_sum += data[array_index];
console.log('sum of values from months',array_sum);
}
} else {
return null;
}
});
};
The problem here is that you are trying to add two strings. The + operator is overloaded in JS, so with numbers it adds them, but with strings it concatenates them. You need to convert them to ints or floats by using parseInt or parseFloat, and get rid of the commas and $ signs out of it, something like:
var num = '$1,100'
parseInt(num.replace(/[$,]/g, ''))
Which would give 1100 if you printed it. After they are in number format, you can sum them.
Or if you have the choice to store the numbers in your array as numbers, without the string formatting to start off with, go with that. So much easier.

Splitting a number into an array

Alright so I'm trying to completely split a number into an Array. So for example:
var num = 55534;
var arr = []; <- I would want the Array to look like this [5,5,5,3,4]
Basically i want to to completely split the number apart and place each Number into its own element of the array. Usually in the past i would just convert the number into a string then use the .split() function. This is how i use to do it:
num += "";
var arr = num.split("");
But this time i actually need to use these numbers, so they can not be strings. What would you guys say be the way of doing this?
Update, after the edit for some reason my code is crashing every run:
function DashInsert(num) {
num += "";
var arr = num.split("").map(Number); // [9,9,9,4,6]
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1){
arr.splice(i,0,"-");
}// odd
}
return arr.join("");
}
String(55534).split("").map(Number)
...will handily do your trick.
You can do what you already did, and map a number back:
55534..toString().split('').map(Number)
//^ [5,5,5,3,4]
I'll do it like bellow
var num = 55534;
var arr = num.toString().split(''); //convert string to number & split by ''
var digits = arr.map(function(el){return +el}) //convert each digit to numbers
console.log(digits); //prints [5, 5, 5, 3, 4]
Basically I'm converting each string into numbers, you can just pass Number function into map also.

Formatting number like 22,55,86,21,28 [duplicate]

This question already has answers here:
How can I convert a comma-separated string to an array?
(19 answers)
Closed 9 years ago.
I need to know how i can use javascript to separate a string like 22,44,85,63,12 to individual numbers without the commas e.g.:
22
44
85
63
12
var a = "one,two,three".split(",") // Delimiter is a string
for (var i = 0; i < a.length; i++)
{
alert(a[i])
}
You need the .split() method like this:
var str = "22,44,85,63,12";
var res = str.split(",");
res will then be a array of your numbers.
Here is a Fiddle
Use the split and join methods
var csv = '22,44,85,63,12';
var ssv = csv.split(',').join(' ');
First split the strings -
var str = ' 22,44,85,63,12';
var arr = str.split(',');
Then create an array of numbers. Check if the element is a number first though.
var numberArr = new Array();
var number;
for(var i = 0; i < arr.length; ++i)
{
number = parseInt(arr[i], 10);
if(!isNaN(number ))
{
numberArray.push(number);
}
}
Try -
var commaSepStr = "22,44,85,63,12";
var spaceSepStr = commaSepStr.replace(/,/g,' ');
This does a global replace. From what i understood, you want the output to be a string and not an array.
Use .split() for extracting the array of number-strings, and .map() for converting those number-strings to Number:
var str = "22,44,85,63,12";
var numbers = str.split(",").map(Number); //[22,44,85,63,12]
If you just want to replace the commas with a blank space how about using
string.replace(/,/g,' ');
but if you want them as separate integers then use var nums = string.split (",");

how to make string as array in java script?

I have a string value like:
1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i
I need to convert it into array in JavaScript like
1 2 3
4 5 6
7 8 9
etc.
Can any one please suggest me a way how to do this?
You are looking for String.split. In your case, you need to split twice. Once with ; to split the string into chunks, then separately split each chunk with , to reach the array structure you are looking for.
function chunkSplit(str) {
var chunks = str.split(';'), // split str on ';'
nChunks = chunks.length,
n = 0;
for (; n < nChunks; ++n) {
chunks[n] = chunks[n].split(','); // split each chunk with ','
}
return chunks;
}
var arr = chunkSplit("1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i");
If you need a multi-dimensional array you can try :
var array = yourString.split(';');
var arrCount = array.length;
for (var i = 0; i < arrCount; i++)
{
array[i] = array[i].split(',');
}
Try the following:
var yourString = '1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var array = [];
yourString.split(';').forEach(function(value) {
array.push(value.split(','));
});
jsFiddle Demo
Note: .forEach() not supported in IE <=8
The following split command should help:
yourArray = yourString.split(";");

Javascript array from string of numbers

I am trying to work with arrays in javascript. Consider the following code:
var visList = '1234,5678,9'
var visListArray = new Array(visList);
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
Why doesn't this split the array into individual numbers instead of all of them clumped together?
Any help would be really appreciated.
Many thanks
Create the array by calling split() on the string:
var visList = '1234,5678,9'
var visListArray = visList.split(",");
You cannot substitue a string that looks like code for actual code. While this would work:
var visListArray = new Array(1234,5678,9);
Yours doesn't because the string is not interpreted by the Array constructor as 3 comma separated arguments, it is interpreted as one string.
Edit: Note that calling split() on a string results in an Array of strings. If you want an Array of numbers, you'll need to iterate the Array converting each string to a number. One convenient way to do that is to use the map() method:
visListArray = visList.split(",").map(function (item) {
return +item;
});
See the compatibility note for using map() in older browsers.
because its an string, try this:
var visList = '1234,5678,9'
var visListArray = [].concat(visList.split(','));
for (i = 0; i <= visListArray.length - 1; i++) {
alert(visListArray[i]);
}
You have to use string.split
var visList = '1234,5678,9'
var visListArray = visList.split(",");
for (i = 0; i <= visListArray.length - 1; i++)
{
alert(visListArray[i]);
}
To convert a symbol-separated list into an array, you may use split(symbol):
var list = "1221,2323,4554,7667".split(",");
for (var i = 0, il = list.length; i < il; i++) {
alert( +list[i] ); // a casting from string to number
}

Categories

Resources