Removing quotes from each string in an array - Javascript - javascript

I've searched here: http://w3schools.com/jsref/default.asp but could not find any convenience method to perform this function. If I have an array var arrayOfStrings = ["20","10","30","100"], is there a quick way to remove all quotes (") from each string in this array without having to loop through?
I essentially want to create this: var arrayOfNumbers = [20,10,30,100]
Thanks

If you want number conversion, you can do it like this...
var arrayOfNumbers = arrayOfStrings.map(Number);
The .map() method creates a new array populated with the return value of the function you provide.
Since the built-in Number function takes the first argument given and converts it to a primitive number, it's very usable as the callback for .map(). Note that it will interpret hexadecimal notation as a valid number.
Another built-in function that would accomplish the same thing as the callback is parseFloat.
var arrayOfNumbers = arrayOfStrings.map(parseFloat)
The parseInt function however will not work since .map() also passes the current index of each member to the callback, and parseInt will try to use that number as the radix parameter.
MDN Array.prototype.map (includes compatibility patch)
DEMO: http://jsfiddle.net/UDWvH/
[
20,
10,
30,
100
]

You could try like this:
for(var i = 0; i < myArray.length; i++)
{
myArray[i] = parseInt(myArray[i], 10);
}
Have a look to the parseInt function.

For browsers that support JSON.parse:
var arr = ["20","10","30","100"];
var newArr = JSON.parse("[" + arr.join() + "]");
console.log(typeof arr[0]); //string
console.log(typeof newArr[0]); //number

You do not need to do anything, the double quotes in JavaScript are identifiers that state that the data within them is a string. This means they are not part of the array or data itself.
You can loop using a standard For loop.

Related

How to use filter function on string

I have a string that looks like this: (5 Sonuç)
How do I extract number using filter function and not any string related function?
Filter function works on array but how do I make it work for a string
I can't use replace or match functions.
You can use filter on a string by calling Array.prototype.filter.call with your string as the "this" argument and the filter function as second arguments.
example :
var str = "5 dfkdf9 eofh"
let res = Array.prototype.filter.call(str, n=>!isNaN(parseInt(n)))
console.log(res)
Use the split() function to return an array then use the filter() function to take out the non-numbers in the array.
You can then convert back to a string (if needed) using string related functions
let myString = "5 Sonuç"
let myNum = myString.split("").filter(e => !isNaN(e));
console.log(myNum)
You can use the spread operator:
const str = "test99"
[...str].filter(c => c == "99");
And if, you faced the error:
Type 'IterableIterator' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.
Instead of
[...str]
you can rely on
Array.from(str)
More on downlevelIteration

InArray returning -1 with matching value

var x = new Array(10);
$.inArray(10,x);
#Returns -1
Fiddle
I've come across this weird issue, checking a value in an array with $.inArray, really simple.
But, if the array only has one value in it, inArray returns -1.
If I add another value to the array, it works as expected.
This only happens with integers and not with strings.
What's going on?!
If you want to create an array with the one number(10) inside you should use bracket literal:
var x = [10];
$.inArray(10,x);
Or with push:
var x = new Array();
x.push(10);
Obviously the first one is more readable and faster to write.
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. Note that this special case only applies to JavaScript arrays created with the Array constructor, not with array literals created with the bracket syntax.
If the only argument passed to the Array constructor is an integer, a new, empty JavaScript array and its length is set to that number
MDN
Fixed fiddle
I suggest to check documentation for arrays in JavaScript, link: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array
In your case, by using:
var x = new Array(10);
It creates an array with length 10 and each item of the array is undefined
I suggest to use:
var x = [10];
this is an array with one item at index 0 that has value 10.
var x = new Array(10); creates an array with 10 slots, not an array that contains "10"

array.splice not working

i want to remove array element, but giving error while using splice,
i m using following function
with myAra as global var,
but in console ,it is giving me an error, TypeError: myAra.splice is not a function
var myAra = Array();
function charCounts(e,textAreaId)
{
myAra = $("#"+textAreaId).val();
var countNewLines = stringOccurrences(myAra, "\n");
if(myAra.length>75)
{
for (var i = 75; i >myAra.length; i++)
{
myAra.splice(i, 1);
}
$("#"+textAreaId).val(myAra);
}
}
myAra is a String, not an Array, at the point when you call splice. It has the value of the element.
This is a nice example of why globals are EVIL, sure you declared the variable an array (badly): var myAra = Array() (I'll explain at the end what's bad about this), but later on:
myAra = $("#"+textAreaId).val();//returns a string, variable is now a string, not an array
You've reassigned a string to the array, so the variable now references a string constant, and cannot be used as an Array (not safely, in a X-browser way at least).
Array() is bad, why? Well, for starters, you're calling a constructor, but you're not using the new keyword. With arrays that's not a big problem (it'll return a new instance all the same), but when you start defining your own objects, and constructors, you'll find yourself up to your neck in globals. Also, suppose you wanted an array and initialize the first element to an int: var anArray = new Array(2);, you won't get an array that looks like this: anArray[0] === 2, you'll get anArray === [undefined,undefined]. Compare that to var anArray('2') --> ['2']. Given the fact that JS is loosely typed, and you'll often use variables when initializing an array, it's hard to tell weather or not you're passing a numeric string or a number to the constructor. The best way to initialize arrays is by using the literal notation: [2,3,4], as an added bonus, it requires less typing, too
Replace the following:
if(myAra.length>75)
{
for (var i = 75; i >myAra.length; i++)
{
myAra.splice(i, 1);
}
$("#"+textAreaId).val(myAra);
}
with the below code:
if(myAra.length>75)
{
var moreNum = myAra.length - 75;
myAra.splice(75, moreNum ); // remove all items after the 75th item
$("#"+textAreaId).val(myAra);
}
Note - splice change the actual array, that's why the loop was failing. Hope it helps.
You are assigning a string value directly to the myAra so it will convert it to string ..typeOf myAra. Use myAra[0]=$("#"+textAreaId).val();...since javascript is a loosely coupled language
In the first line you used var myAra = Array(), but the jQuery val() function returns a string.
EDIT: Also I think the prefered way of creating arrays in JS is the var myArray = [], and not using the var myArray = new Array() expression.

Javascript accessing the string variable as array

I just tried this code in Chrome deveoper tools:
var str = "1111111";
str[0] = 2;
2
console.log(str[0]);
1
As you can see, the output was 1, where I expected 2. My conclusion is this is not meant to be working like that, so I ask how would I get this to work - how would I change the first 'item' of the varable str to 2?
That is because in JavaScript strings are immutable objects. You should use substr function:
String.prototype.replaceAt = function (index, char) {
return this.substr(0, index) + char + this.substr(index + char.length);
};
var str = '11111';
console.log(str.replaceAt(0, '2'));
From the rhino book:
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it.
Try this out
str.replace(str.charAt(0), "2")
You need to split the string first.
So something like:
str = str.split('');
Then you can treat it as an array.

Javascript use reserved keyword as key

Doing so
var x = new Array();
x['length']=5;
will make x an array of 5 undefined items, but I actually want to have the value '5' stored at key 'length'.
Is that possible?
In javascript arrays do not have keys. You are looking for objects:
var x = {}
x.length = 5;
I have to parse a file containing many words and store the number of occurences of each word
Use an object, and make the words the keys. You aren't storing sequential / ordered data, so you shouldn't use an array.
var word_count = {};
for (var i; i < words.length; i++) {
var word = words[i];
if (word_count[word]) {
word_count[word]++;
} else {
word_count[word] = 1;
}
If you want to do this you'd be better off creating an object rather than an array. This should give you what you want.
var x = {};
x['length'] = 5;
You can call methods on a javascript object using two different syntaxes. The familiar 'dot' syntax with parens to invoke the method, and the square bracket syntax. You can 'call' a method on a javascript object using the syntax myObj["methodname"](args). This is handy when you want to construct the method name dynamically using strings. Remember, objects in javascript are very much like a hash table (dictionary) where keys denote property and function names. If a key's value holds a function, it can be invoked (using parentheses).
In your example, Array has a method called 'length'. You are inadvertently calling its setter (which sets the length of the array to empty values, i.e., undefined).
Putting that all aside, you really do want a hash (associative array) in this case. An array is an offset indexed data structure.
A simple object literal like myObj = {} will suffice to give you hash semantics (again, objects in javascript are already like hashes) and you can then call myObj.whatever = "some value"
You could use objects instead of arrays to store your data. But if you need to use Arrays (you might need to use their functionality), You could cripple the words and store them as array keys.
Use some kind of simple rule to follow to bypass all the possible keywords. For example prefix all your array keys with a "_" character. This way you could always restore the original words from the keys, by simply removing their first character, and you are sure you are not referencing any specific property of the Array objects (like the length property).

Categories