Javascript array from string of numbers - javascript

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
}

Related

ParseInt elements in array to int

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)

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 (",");

Javascript breaking up string and reverse it

I am trying to figure out how to break up a sting to groups of five and reverse each one individually. I want it to work for any string, (there is no delimiter for splitting)
For example, if the variable is:
Iwanttobreakthisintogroupsoffiveandreverse
I would want it to return:
tnawI erbot ihtka otnis puorg iffos dnaev rever es
How do I go about this?
var str = "Iwanttobreakthisintogroupsoffiveandreverse"
var result = [];
str.replace(/.{1,5}/g, function(m) {
result.push(m.split('').reverse().join(''));
});
result.join(' ');
// "tnawI erbot ihtka otnis puorg iffos dnaev rever es"
var input="Iwanttobreakthisintogroupsoffiveandreverse";
var matches = input.match(/.{1,5}/g);
for (i = 0; i < matches.length; ++i) {
matches[i] = matches[i].split("").reverse().join("");
}
alert(matches);
It pops up tnawI,erbot,ihtka,otnis,puorg,iffos,dnaev,rever,es
You could try this:
var chars = "Iwanttobreakthisintogroupsoffiveandreverse".split('')
var str_rev = []
for (i = 0; i < chars.length; i += 5)
str_rev.push( chars.slice(i, i + 5).reverse().join('') )
Convert to char array using split(''). This allows you to use array methods like reverse and slice
Loop through the char array taking 5 element slices
reverse the elements, join the chars to create a string, and add it to rev_str

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

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(";");

Categories

Resources