Elegant way to convert string of values into a Javascript array? - javascript

I have an ajax request that returns a list of values like this:
"1,2,3,4,5,6"
I need it to be a javascript array with numbers:
[1,2,3,4,5,6]
I tried:
var array = new Array("1,2,3,4,5,6".split(","))
But the numbers are still strings in the output:
["1","2","3","4","5","6"]
Is there a clean way to have it as a numbered array? Preferably without writing a function to iterate through it?

You need to loop through and convert them to numbers, like this:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = +array[i];
Or, the more traditional example:
var array = "1,2,3,4,5,6".split(",");
for(var i=0; i<array.length; i++) array[i] = parseInt(array[i], 10);

A more jQuery-centric approach using jQuery.map():
var str = "1,2,3,4,5,6";
var arr = $.map(str.split(","), function(el) { return parseInt(el, 10); });

Not sure if this counts as writing a function but you can use the map function in jquery. I saw you listed as a tag so I assume you are using:
var stringArray = "1,2,3,4,5,6".split(",");
var numberArray = $.map(stringArray,
function(item, i)
{
return parseInt(item, 10);
});

// jquery must have a way to do what any modern browser can do:
var str= "1,2,3,4,5,6";
var arr= str.split(',').map(Number);
// returns an array of numbers

If you trust the ajax response, and if (for whatever reason) you're committed to not using a loop, you can always go with eval:
var str = "1,2,3,4,5,6";
var array = eval("[" + str + "]");

If you don't wish to expliclty iterate you can use array.map, javascripts map function.
array.map(callbackFunc, array);
var arr = array.map(function(x) {return parseInt(x);}, "1,2,3,4,5,6".split(","));
http://www.tutorialspoint.com/javascript/array_map.htm
Theres probably a better reference somewhere but I don't us javascript enough to have a good favorite reference site.
EDIT - i see jQuery has its own map, thats probably worth looking into.

Related

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

How to strip non integers in array elements in JavaScript

I'm quite new to programming, and I feel that similar questions have been asked before. But I've tried to apply them and know I am missing something fundamental.
Given an array:
var myArray = [24.203, 12*45, 000-1, 4567+00];
I'd like to strip all non integers, so that I have something like this:
var myArray = [24203, 1245, 0001, 456700];
I know of the .replace method, but I can't seem to get it work. Here are four things I've tried:
function stripNonIntegers(arr) {
var x;
this.myArray = myArray;
for(x = 0; x < 10; x++) {
myArray[x] = myArray[x].replace(/\D/g, '');
} }
stripNonIntegers(myArray);
This returns an error saying myArray is undefined.
var x;(myArray); { //I don't like the semicolons but I get an error if I omit them
for(x = 0; x < 10; x++)
{myArray[x] = myArray[x].replace(/\D/g, '');
} }
this returns an error saying x is undefined.
stripNonIntegers= function(arr) {
for (x =0; x<this.length; x++)
myArray.replace(/\D/g,'');};
stripNonIntegers(myArray);
This output is undefined.
var stripNonIntegers= myArray[x]; {
for (x=0; x<myArray.length; x++) {
stripNonIntegers = myArray.replace(/[^\d]/g, '');
} }
And this one also says x is undefined. This post explains how to use the .replace method with a regex of /D to strip non-numerics from a string, but I can't seem to get it to work with an array (not a function). Thus I try to stick a 'for' loop in there so it treats each element as its own string. I know I'm making a stupid mistake, but for all my trying, I can't identify it. I'm shooting in the dark.
Any tips? Thanks in advance.
var myArray = ['24.203', '12*45', '000-1', '4567+00'];
var myNewArray = myArray.map(function(value) {
return parseInt(value.replace(/\D/g, ''), 10);
});
\D is a shorthand character class that matches all non-digits.
The above code works when your array elements are strings.
You have the regular expression right, and you're using replace correctly. Your problem may be that the items in your array are not strings in the code you gave. Just wrap each one in quotes to make them strings:
var myArray = ['24.203', '12*45', '000-1', '4567+00'];
Then, you can map over the array and use your replace call:
var newArray = myArray.map(function (item) {
return item.replace(/\D/g, '');
});
That results in this:
["24203", "1245", "0001", "456700"]
These are still strings, though. To convert them to numbers, you can use parseInt:
var intArray = newArray.map(function (item) {
return parseInt(item, 10);
});
You could do all this in one step, if you prefer:
var newIntArray = myArray.map(function (item) {
return parseInt(x.replace(/\D/g, ''), 10);
});
Of course, if you prefer regular for loops, you could do all this with those. However, I think using map looks a bit cleaner. If you're not familiar with map, check out the MDN docs for the array map function

How to remove duplicate objects from java script array?

I have two arrays as shown below. I want to remove Array2 elements from Array1. How do I do that?(either in plain java script or using ExtJS)
var Array1 = [];
var Array2 = [];
Array1.push(['eth0'], ['eth1']);
Array2.push(['eth1']);
If you have the array filter function available to you, you can do something like the following:
var filteredArr = Array1.filter(function(val){
return Array2.indexOf(val) != -1;
})
I think this will only be supported in newer browsers, though. It's an elegant way to handle the situation, so you may want to take a look at a library like UnderscoreJS which will include filtering, defaulting to the native implementation if available.
If using UnderscoreJS, the code would look very similar:
var filterdArr = _.filter(Array1, function(val) {return Array2.indexOf(val) != -1});
function removeDupes(a1, a2) {
var index = {}, result = [], i, l;
for (i=0, l=a2.length; i<l; i++) {
index['-' + a2[i]] = "";
}
for (i=0, l=a1.length; i<l; i++) {
if (index['-' + a1[i]] !== "") result.push(a1[i]);
}
return result;
}
The index object is for speedy look-up of values so we can test their existence quickly.
The '-' + is to migrate the fact that values could be things like toString that also exist as object properties. When prefixed with a letter that regular JavaScript identifiers cannot start with, every value will be safe for use as an object key.
Example:
removeDupes([1,2,3,4], [2,4,5]);
// -> [1,3]
removeDupes([2,4,5], [1,2,3,4]);
// -> [5]
Check this link: http://www.developersnippets.com/2008/10/30/remove-duplicates-from-array-using-javascript/. Concat your arrays with concat() and call uniqueArr().

Simple way to import and export and store Arrays

For example I have something like this.
var Ar : Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
And I need to store it in simple text file. Like this
ArText : String ;
ArtText = "0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
You got the point.
What is best way to convert Array in to a readable string, and then back? Javascript code will be best, but you can use almost any similiar.
My initial impulse was to convert it directly to JSON, but then I realised that JSON.stringify() would return something like this:
["apple",null,null,"pineapple",null,null,null,null,null,null,null,null,"car",null,null,null,null,null,null,null,null,"apple",null,null,null,null,null,null,null,null,null,null,null,"dog",null,null,null,null,null,null,null,"cat"]
Because your array has a bunch of undefined slots that all become null because JSON doesn't support undefined values. Which would be OK if you just need to store it except then when you convert it back to an array you'd end up with nulls everywhere instead of undefined so you'd have to allow for that (not a big deal) but in any case it sounds like you want it to be human-readable too.
So instead I suggest you convert it to an object and then convert the object to JSON using JSON.stringify(). To convert it back you use JSON.parse() to turn your string into an object, then loop through the object properties to create a sparse array.
What I'm proposing would result in a JSON string like this:
{"0":"apple","3":"pineapple","12":"car","21":"apple","33":"dog","41":"cat"}
The code:
function sparseArrayStringify(arr) {
var obj = {},
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
obj[i] = arr[i];
return JSON.stringify(obj);
}
function parseToSparseArray(str) {
var arr = [],
obj = JSON.parse(str),
k;
for (k in obj)
arr[k] = obj[k];
return arr;
}
var stringifiedArray = sparseArrayStringify(Ar); // where Ar is your array
// and change it back
var anArray = parseToSparseArray(stringifiedArray);
Working demo: http://jsfiddle.net/XXqVD/
Note: in my parseToSparseArray() function I didn't bother testing that the properties of the object in the string being parsed actually are non-negative integers, but you can add that if desired.
Newer browsers support the JSON object with associated methods, or for older browsers you can include the json2.js library.
By the way, the code in your question is invalid JavaScript: you can't declare variables with a type in JS. See the examples in my code for how to declare arrays, objects, etc.
EDIT: OK, I don't know why on earth you'd want the non-JSON version when JSON is a well known standard format, but here are some untested functions that read and write exactly the format from the question:
"0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
Note that your proposed format won't work if any of the array elements contain commas or hyphens. Which is why JSON is the way you should go. Anyway:
function serialiseArray(arr) {
var workingArray = [],
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
workingArray.push(i + "-" + arr[i]);
return workingArray.join(",");
}
function deserialiseArray(str) {
var arr = [],
items = str.split(","),
item,
i;
for (i=0; i < items.length; i++) {
item = items[i].split("-");
arr[item[0]] = item[1];
}
return arr;
}
If it's just strings in the array, you could use the join() method on the Array object to create a comma separated string, and then use the split() method on the String object to convert the string back to an array.
var Ar = new Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
var stringRepresentation = Ar.join(",");
var backToArray = stringRepresentation.split(";");
You can see this working here; http://jsfiddle.net/ykQRX/. Note I've also fixed your invalid JavaScript (var Ar = new Array;).

How to append (connect) strings to construct a new string?

I have a array of strings:
str[1]='apple';
str[2]='orange';
str[3]='banana';
//...many of these items
Then, I would like to construct a string variable which looks like var mystr='apple,orange,banana,...', I tried the following way:
var mystr='';
for(var i=0; i<str.length; i++){
mystr=mystr+","+str[i];
}
Which is of course not what I want, is there any efficient way to connect all this str[i] with comma?
just use the built-in join function.
str.join(',');
Check out join function
var str = [];
str[0]='apple';
str[1]='orange';
str[2]='banana';
console.log(str.join(','));
would output:
apple,orange,banana
The fastest and recommended way of doing this is with array methods:
var str = [];
str[1] = 'apple';
str[2] = 'orange';
str[3] = 'banana';
var myNewString = str.join(',');
There have been various performance tests showing that for building strings, using the array join method is far more performant than using normal string concatenation.
You need this
var mystr = str.join(',');
how about 'join()'?
e.g.
var newstr = str.join();
You're looking for array.join i believe.
alert(['apple','orange','pear'].join(','));
Is this what you want?
var str = new Array(); //changed from new Array to make Eli happier
str[1]='apple';
str[2]='orange';
str[3]='banana';
var mystr=str[1];
for(var i=2; i<str.length; i++){
mystr=mystr+","+str[i];
}
console.log(mystr);
would produce
apple,orange,banana

Categories

Resources