JavaScript split string to array of int - javascript

I have a string that's on the page and from which I want an array of int.
<div id="TheData">2,3,0,43,23,53</div>
I'm writing this:
var ArrayData = ($('#TheData').html()).split(',');
However, ArrayData becomes an array of strings. How can I get an array of ints? Note that some of the elements in the HTML can be equal to 0.
Thanks.

var ArrayData = $('#TheData').html().split(',').map( Number );
Add Array.prototype.map() to older browsers with the code from MDN.
You can use jQuery's $.map() in the same manner, though it won't work with $.prototype.map().
var ArrayData = $.map( $('#TheData').html().split(','), Number );

var ArrayData = $.map($('#TheData').text().split(','), function(value){
return parseInt(value, 10);
// or return +value; which handles float values as well
});
You can use $.map to transform the array of strings to ints by calling parseInt on each of the elements in the array

Pure Javascript solution:
const elementText = document.getElementById('divSourceID').innerText;
const numericList = elementText.split(',').map(Number);
For more information:
getElementById: "The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly. (...)". Source: developer.mozilla.org.
Array.prototype.map: "The map() method creates a new array populated with the results of calling a provided function on every element in the calling array". Source: developer.mozilla.org.
array.map(Number): This call means the first received argument will be automatically converted into number and results in the same as if you explicitly declare the arrow function:
const numericList = elementText.split(',').map(Number);
same result as:
const numericList = elementText.split(',').map(str => Number(str));
JIT: Special thanks to #Robbendebiene for the excellent code review, simplifying the previous code.

var ArrayData = $('#TheData').text().split(',').map(Number);
You can find more here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Here is a simple answer
let x = "1,2,3,4";
let result = x.split(",").map((e) => parseInt(e));
console.log(result);

var ArrayData = $('#TheData').html().split(',').map( d => { return parseInt(d) });
Use map function after Split, in callback of map you can parse that Integer

Related

Return an Array of Abbreviated Strings with .filter() - JavaScript

If I have an array of strings that I would like to abbreviate with the filter() method.
How would I use filter() in combination with str.substring (or another string method if applicable)?
In the following code I would like to return the first four characters of each name, but it doesn't seem to be working.
JavaScript
let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;
nickNames = poshNames.filter(function(name){
return name.str.substring(0,4);
});
You should use map:
const poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth", "H"];
const nickNames = poshNames.map(name => name.substring(0,4));
console.log(nickNames);
Use map instead of filter
and it will work:
let poshNames = ["Markol", "Andile", "Jazzmine", "Famisynth"];
let nickNames;
nickNames = poshNames.map(function(name) {
return name.substring(0,4);
});
What filter does is essentially return an array that contains every element in the array for which the function returns true.
What map does, on the other hand, is return an array that contains the value the function returns for every value in the array.
Note: Both methods return a new array without affecting the original.

Get data from this json string

I have a json string
["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]
I need to get at the data only and I want to extract the string to get the following :
https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
I have tried to use JSON.parse but this does not seem to work
Any help woul dbe appreciated
[] represents an array on JSON. {} represents an Object.
So in order to fetch the first element from you json string, you have to parse the string as a JSON element ;
var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');
OR when you HAVE a json array already;
var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
Then, go on and fetch the first value from your array which has index 0 as in all programming languages.
var url = arr[0];
It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:
var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
Be aware of the difference between an array, and a JSON object.
I have given some examples of the differences and how to access them.
// This is an array containing 1 value.
myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
// it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value.
var example1 = [myobj];
document.write("This is my single value array:<br>" + example1 + "<br><br>");
// This is probably best practice regardless of the number of items in the array.
var example2 = myobj[0];
document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>");
// This is a JSON object
myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"}
// You access the value of the URL like this:
var example3 = myJsonObj.url;
document.write("Here is the value from a JSON object:<br>" + example3 );
Hope this helps
Just use parse function:
var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);
https://jsfiddle.net/esouc488/1/

pass array to method with condition

Im using the following code to split array which is working,
I need to pass some value when array
for examle here is split the value to array
var myArr = val.split(/(\s+)/);
and if array in place 2 is empty I need to use the method like following
pass empty array in second arg
var val = process.run(myArr[0], [], options);
if the array place 2 is not empty I need to pass it like following
var val = process.run(myArr[0], [myArr[2]], options);
The second arg is array inside arry with the value of 2
there is nice way to do it instead of if on the method ?
I would create a function, as Dave Newton recommends. I could take the initial val and options as an argument and return the result of process.run:
function runProcess(val, options) {
var myArr = val.split(/(\s+)/);
var argArray = [];
if(myArr[2]) {
argArray.push(myArr[2]);
}
return process.run(myArr[0], argArray, options);
}
Since I don't know what the function exactly does, the name of the function and variables are pretty arbitrary. Feel free to change them to your needs.
If myArr[2] is a flat array and will always be flat, why not...
var val = process.run(myArr[0], [].concat(myArr[2]), options);

Access value from JavaScript object via array-string

my problem is that i have a json-object with and array into here an example.
var object = {
'items':['entry1','entry2']
}
I want to access 'entry2' over a constant string that I receive and shouldn't be changed.
var string = 'items[1]';
The only way I'm solving this problem is over the eval function...
eval('object.'+string);
This returns me entry2.
Is there any other way to achieve this without using eval()?
Like object[string] or object.string
Supposing your string is always the same form, you could extract its parts using a regex :
var m = string.match(/(\w+)\[(\d+)\]/);
var item = object[m[1]][+m[2]];
Explanation :
The regex builds two groups :
(\w+) : a string
\[(\d+)\] : some digits between brackets
and those groups are at index 1 and 2 of the array returned by match.
+something parses the number. It's not strictly needed here as the array accepts a string if it can be converted but I find the code more readable when this conversion is explicited.
On top of dystroy's anwser, you can use this function:
function getValueFromObject(object, key) {
var m = key.match(/(\w+)\[(\d+)\]/);
return object[m[1]][+m[2]];
}
Example:
var object = {
'items':['entry1','entry2']
}
var string = 'items[1]';
var value = getValueFromObject(object, string); //=> "entry2"
First, you can get the array from inside:
var entries = object.items // entries now is ['entry1','entry2']
Then you need to index that to get the second item (in position 1). So you achieve what you want with:
var answer = entries[1] // answer is now 'entry2'
Of course, you can combine this to get both done in one step:
var answer = object.items[1] // answer is now 'entry2'
... I can see this is a contrived example, but please don't call your Objects 'object', or your Strings 'string' :s
try something like this
object.items[1];

get the second to last item of an array?

How can I get the last second item in an array?
For instance,
var fragment = '/news/article-1/'
var array_fragment = fragment.split('/');
var pg_url = $(array_fragment).last()[0];
This returns an empty value. But I want to get article-1
Thanks.
Not everything has to be done using jQuery.
In plain old javascript you can do:
var pg_url = array_fragment[array_fragment.length - 2]
Easier and faster :)
Looks like you can also use Javascript's slice method:
var path = 'a/b/c/d';
path.split('/').slice(-2, -1)[0]; // c
You can also think of "second to last element in the array" as "second element of the array reversed":
var path = 'a/b/c/d';
path.split('/').reverse()[1]; // c
Step 1: Use split() Method to split the elements into an array.
var fragment_arr = fragment.split("/");
Step 2: Use slice(-2) Method to select last 2 element from array, the negative number to select from the end of an array.
var lastTwo = fragment_arr.slice(-2);
Step 3: lastTwo array contains last two elements of fragment_arr, now you can access like this
var element = lastTwo[0];
alert(element);
Short answer : you can combine step 2 and 3 like below
var element = fragment_arr.slice(-2)[0];
alert(element);
arr.at(-2); will do exaclty that - it returns last second item in an array.
const arr = [1,2,3,4];
arr.at(-2); // Returns 3
The at() method takes a positive or negative integer and returns the item at that index. Negative integers count back from the last item in the array.
It is fully supported by browsers.
Docs: Array/at
This can be covered by lodash _.nth:
var fragment = '/news/article-1/'
var array_fragment = _.split(fragment, '/');
var second_last = _.nth(array_fragment, -2);
console.log(second_last);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
var pg_url = array_fragment[array_fragment.length -2]
array_fragment isn't a jquery variable, it's a plain old javascript variable so no need for $()
This question is old but still relevant. Slice with length-1 is the best bet, but as an alternative with underscore/lodash:
_.initial() gets all but the last
_.last() gets the last
So you could do
_.last(_.initial([1,2,3,4]))
or chained:
_.chain([1,2,3,4])
.initial()
.last()
.value();
which gives you back 3.
Or in the original question:
var fragment = '/news/article-1/'
var array_fragment = fragment.split('/');
var pg_url = _.chain(array_fragment).initial().last().value();
If accessing arrays in reverse is something that is going to be often required, and not just the second to last index, a simple expansion to the prototype could be used.
When extending something as large and used as the Array prototype ensure that you are not going to affect any other part of its use. This is done by making sure that the property is not enumerable so that for in will not choke anywhere else (some people and libraries use for in to iterate arrays).
Object.defineProperty(Array.prototype, 'rev', {
enumerable: false,
value: function(index){
return this[this.length - 1 - index];
}
});
document.write([1,2,3,4,5,6].rev(1));
And now you can use zero based indexing in reverse.
var a = [1,2,3,4];
var b = a.slice(-2,-1);
console.log(b);
The answer is [3].You just have to mention the start and end for slice.
The following works for a string with nth 'url' parts.
var fragment = '/t/e/s/t/i/n/g/';
var fragment = '/t/';
If the fragment is of variable length, you need a solution that works for various fragment sizes.
var fragment = '/news/article-1/';
var array_fragment = fragment.split('/');
Split separates the fragment string where it finds '/'s. Split takes the value before and after the split character. In this case there is nothing before the first slash or after the last slash. The empty values are added to the array_fragment in the first and last array positions.
jQuery
var pg_url = $(array_fragment)[$(array_fragment).length - 2];
javascript
var pg_url = array_fragment[array_fragment.length - 2];
As you can see, jQuery is not needed for this solution.
Array_fragment.length - 2 is counting the length of the array_fragment, and selecting the second item from the end. The last value is "" due to Split('/') adding an empty value to the end of the array_fragment array.
Simplified and all put together:
var f = '/t/e/s/t/i/n/g/'.split('/');
f[f.length - 2]
const myArray: Array<string> = ['first', 'second', 'third'];
Split myArray by second last item.
const twoItemsFromEnd = myArray.slice(-2); //Outputs: ['second', 'third']
Then
const secondLast = twoItemsFromEnd[0];
Or:
const secondLast = (params.slice(-2))[0];

Categories