How to manipulate string in an array - javascript

I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript

use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)

I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));

This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])

Related

Storing the word length in javascript array

I am puzzled as to why I can not store the word length in a javascript array.
I have tried
var i = [];
i["length"] = "ABC";
i["len"+"gth"] = "ABC";
but both aren't accepted in javascript. Can anyone explain it, and is there a way that I can store the word length in an array as above.
Since some asked for more detail. I am creating a list of words that I need to do a lookup at and find the value to display to the user. My list contains for example:
localVars.FunctionDic = [];
localVars.FunctionDic["lastindexof"] = "LastIndexOf(text, textToLocate)";
localVars.FunctionDic["specificindexof"] = "SpecificIndexOf(text, textToLocate, indexNumber)";
localVars.FunctionDic["empty"] = "Empty(text)";
localVars.FunctionDic["length"] = "Length(text)";
everything works except for the "length"
and I am using an array since I need to test if the word a user search for is in my array, and if it is display the value, if it is not, show nothing
It does not work because you are trying to write a string to a property that only allows a number.
From MDN: The length property of an object which is an instance of type Array sets or returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.
With the limited details in your question it is hard to tell what you are actually trying to accomplish. It seems like you want to use an array like an object. If that is the case, use an object.
var i = {};
i["length"] = "ABC";
Based on the expected output, I believe you should be using an object not an array.
const FunctionDic = {
lastindexof: "LastIndexOf(text, textToLocate)",
specificindexof: "SpecificIndexOf(text, textToLocate, indexNumber)",
empty: "Empty(text)",
length: "Length(text)",
};
console.log(FunctionDic["lastindexof"]);
console.log(FunctionDic["specificindexof"]);
console.log(FunctionDic["empty"]);
console.log(FunctionDic["length"]);
To store the word length in an array you can do:
var i = ["length"]
If you want to store the length of a word in an array you can do:
var lengthOfHello = "hello".length
var i = [lengthOfHello]
var i = ["ABC"];
console.log(new Array(i[0].length).length);

HashMap example in pure JavaScript

I have String like below.
10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah
I need a way to retrieve the string by giving the ID.
E.g.: I give 20; return 150~Jude|440~Niroshan.
I think I need a HashMap to achieve this.
Key > 20
Value > 150~Jude|440~Niroshan
I am looking for an pure JavaScript approach. Any Help greatly appreciated.
If you're getting the above string in response from server, it'll be better if you can get it in the below object format in the JSON format. If you don't have control on how you're getting response you can use string and array methods to convert the string to object.
Creating an object is better choice in your case.
Split the string by # symbol
Loop over all the substrings from splitted array
In each iteration, again split the string by = symbol to get the key and value
Add key-value pair in the object
To get the value from object using key use array subscript notation e.g. myObj[name]
var str = '10=150~Jude|120~John|100~Paul#20=150~Jude|440~Niroshan#15=111~Eminem|2123~Sarah';
var hashMap = {}; // Declare empty object
// Split by # symbol and iterate over each item from array
str.split('#').forEach(function(e) {
var arr = e.split('=');
hashMap[arr[0]] = arr[1]; // Add key value in the object
});
console.log(hashMap);
document.write(hashMap[20]); // To access the value using key
If you have access to ES6 features, you might consider using Map built-in object, which will give you helpful methods to retrieve/set/... entries (etc.) out-of-the-box.

producing a word from a string in javascript

I have a string which is name=noazet difficulty=easy and I want to produce the two words noazet and easy. How can I do this in JavaScript?
I tried var s = word.split("=");
but it doesn't give me what I want .
In this case, you can do it with that split:
var s = "name=noazet difficulty=easy";
var arr = s.split('=');
var name = arr[0]; //= "name"
var easy = arr[2]; //= "easy"
here, s.split('=') returns an array:
["name","noazet difficulty","easy"]
you can try following code:
word.split(' ').map(function(part){return part.split('=')[1];});
it will return an array of two elements, first of which is name ("noazet") and second is difficulty ("easy"):
["noazet", "easy"]
word.split("=") will give you an array of strings which are created by cutting the input along the "=" character, in your case:
results = [name,noazet,difficulty,easy]
if you want to access noazet and easy, these are indices 1 and 3, ie.
results[1] //which is "noazet"
(EDIT: if you have a space in your input, as it just appeared in your edit, then you need to split by an empty string first - " ")
Based on your data structure, I'd expect the desired data to be always available in the odd numbered indices - but first of all I'd advise using a different data representation. Where is this string word coming from, user input?
Just as an aside, a better idea than making an array out of your input might be to map it into an object. For example:
var s = "name=noazet difficulty=easy";
var obj = s.split(" ").reduce(function(c,n) {
var a = n.split("=");
c[a[0]] = a[1];
return c;
}, {});
This will give you an object that looks like this:
{
name: "noazert",
difficulty: "easy"
}
Which makes getting the right values really easy:
var difficulty = obj.difficulty; // or obj["difficulty"];
And this is more robust since you don't need to hard code array indexes or worry about what happens if you set an input string where the keys are reversed, for example:
var s = "difficulty=easy name=noazet";
Will produce an equivalent object, but would break your code if you hard coded array indexes.
You may be able to get away with splitting it twice: first on spaces, then on equals signs. This would be one way to do that:
function parsePairs(s) {
return s.split(' ').reduce(
function (dict, pair) {
var parts = pair.split('=');
dict[parts[0]] = parts.slice(1).join('=');
return dict;
},
{}
);
}
This gets you an object with keys equal to the first part of each pair (before the =), and values equal to the second part of each pair (after the =). If a string has multiple equal signs, only the first one is used to obtain the key; the rest become part of the value. For your example, it returns {"name":"noazet", "difficulty":"hard"}. From there, getting the values is easy.
The magic happens in the Array.prototype.reduce callback. We've used String.prototype.split to get each name=value pair already, so we split that on equal signs. The first string from the split becomes the key, and then we join the rest of the parts with an = sign. That way, everything after the first = gets included in the value; if we didn't do that, then an = in the value would get cut off, as would everything after it.
Depending on the browsers you need to support, you may have to polyfill Array.prototype.reduce, but polyfills for that are everywhere.

How to get the last element of a json file with jquery

$.getJSON('./file-read?filename='+filename+'&parameter='+parameter, function(data) {
var firstElement = data[0][0];
var lastElement = ?
});
I try to find out the last Element in my JSON file.
My JSON File looks like this:
[[1392418800000,6.9],[1392419400000,7],[1392420000000,7.1],[1392420600000,7.2],[1392421200000,7.2]]
can anybody help me to read extract the last date(1392421200000) ?
Just pick the (length - 1)th element with this:
var lastElement = data[data.length-1][0];
Another way is to use array methods, e.g. pop which will return the last element of the array:
var lastElement = data.pop()[0];
N.B.: The first approach is the fastest way of picking the last element, however the second approach will implicitly remove the last element from data array. So if you plan to use the initial array later in your code, be sure to use either the first method or alternative solution provided by #matewka.
VisioN's answer is nice and easy. Here's another approach:
var lastElement = data.slice(-1)[0];
// output: [1392421200000,7.2]
Negative number in the slice method makes the slice count from the end of the array. I find this method more compact and simpler but the disadvantage is that it returns a smaller, 1-element array instead of the element you wanted to fetch. If you want to fetch only the timestamp you'd have to add another [0] to the end of the expression, like this:
var lastElement = data.slice(-1)[0][0];
// output: 1392421200000
You can use :
var data = " any json data";
var lastelement = data[ Object.keys(obj).sort().pop() ];
Object.keys (ES5, shimmable) returns an array of the object's keys. We then sort them and grab the last one.

Sending an array with JavaScript to the next page

The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.

Categories

Resources