I have a dynamically generated large string which I am splitting.
var myString="val1, val, val3, val4..... val400"
I do a simple split on this string,
myString= myString.split(',')
getting the following:
myString[1] // gives val1
myString[2] // gives val2
myString[3] // gives val3
.
.
.
myString[400] // gives val400
Is there a way to make the following?
myString[101] // gives val1
myString[102] // gives val2
myString[103] // gives val3
.
.
.
myString[500] // gives val400
Arrays are zero-based, so in fact in your version you have indices 0 up to 399 rather than 1 to 400.
I'm not quite sure why you'd want 100 items padding out the start of the array, but for what it's worth, here's a short way of doing what you want. It's also one of the few times the Array constructor is actually useful:
var parts = new Array(100).concat(myString.split(','));
We can add elements at the beginning of an array by using the unshift() method. Here is the general syntax for using it.
scripts.unshift("VAL01","VAL02");
Here scripts is our array object, and we are adding two new elements, VAL01 and VAL02, at the beginning of this array by using the unshift() method.
So you can use unshift to add 100 array elements before your split string.
If you don't want 100 padding elements at the beginning (index 0 to 99), you don't want to use an array. Arrays are always continious with the indexes. So you are probably looking for an object.
var obj = {}
for ( var i = 0; i < arr.length; i++ )
{
obj[ i + 100 ] = arr[i];
}
However you shouldn't do it like that, because using an object reduces your possibilities to work with. If you don't want to add another 100 elements at the beginning (in which case you can just add those to the beginning of the existing array), then you should rather work with the original array and simply shift the index manually when you access it.
Are you sure that you need this? You could simply substract 100 from your offset to get to that value. To this, arrays in JavaScript are zero-indexed. Which means that the first item can be accessed using myString[0] rather than myString[1].
Use a function to read the offset value
function getOffSetValue(arr, index, offset)
{
if(offset == undefined)
offset = 100;
return arr[index - offset];
}
var st = "val1,val2,val3,val4,val5";
var a = st.split(',');
console.log(getOffSetValue(a, 102));
Related
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.
$.getJSON('./file-read?filename='+filename+'¶meter='+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.
I have a comma separated list of values, and I need to remove the one that is equal to a certain value.
myList = '10,20,30';
myList.remove(20); // === '10,30'
I'm dashing off, but the component parts of the solution will probably be:
String#split, which splits a string into an array based on a delimiter.
Array#indexOf, which finds an entry in an array (some older browsers may not have it; on those, you'll have to do a loop).
Array#splice, which (amongst other things) removes entries from an array.
Array#join, which joins an array into a string using a given delimiter.
...possibly with something mixed in there to deal with stray spaces, if they're a possibility.
Or of course, you could just put commas at either end and then search for ",20," with String#indexOf and use String#substring to grab the bits in front of and behind it. But what fun is that. ;-) (And it seems a bit fragile.)
Here is some tested and jslinted code that does what you're asking for.
if (!String.prototype.removeListItem) {
String.prototype.removeListItem = function(value, delimiter) {
delimiter = delimiter || ',';
value = value.toString();
var arr = this.split(delimiter),
index = arr.indexOf(value);
while (index >= 0) {
arr.splice(index, 1);
index = arr.indexOf(value);
}
return arr.join(delimiter);
};
}
alert('10,20,30,120,200'.removeListItem(20));
// yields '10,30,120,200'
However, I question why you would do this. Arrays should be stored in array objects, not in string literals. If you need to display the list, then convert to a delimited list at display time. If your input is a string, then split it at input time and keep it internally as an array. I really strongly believe this is the best practice for you and in the long run you will have much easier to maintain code that is much easier to understand.
var myArray = myList.split(',');
myArray.splice(1,1); // Remove one element at index 1, which is 20 in your example
myList = myArray.toString();
A few people almost had replace working.
var lists = ['20', '10,20', '20,30', '10,20,30', '120,200,2020'];
for (var i=0; i<lists.length; ++i) {
lists[i] = lists[i].replace(/(^|,)20,|(^|,)20$/,'$1');
}
Result:
["", "10", "30", "10,30", "120,200,2020"]
Split the string to give you an array. Once you have it in an array, remove the element you need removed. Then output the string again.
Or you could find and replace '20', with ''.
Can anyone explain why the second alert says 0 ?
var pollData = new Array();
pollData['pollType'] = 2;
alert(pollData['pollType']); // This prints 2
alert(pollData.length); // This prints 0 ??
The length of the array is only changed when you add numeric indexes. For example,
pollData["randomString"] = 23;
has no effect on length, but
var pollData = [];
pollData["45"] = "Hello";
pollData.length; // 46
changes the length to 46. Note that it doesn't matter if the key was a number or a string, as long as it is a numeric integer.
Besides, you are not supposed to use arrays in this manner. Consider it more of a side effect, since arrays are objects too, and in JavaScript any object can hold arbitrary keys as strings.
Because you haven't put anything into the array yet. You've only been assigning to a dynamically-created pollType attribute on the array object.
If you use numeric indices, then the array automagically takes care of length. For example:
var arr = [ ]; // same as new Array()
arr[2] = 'Banana!';
alert(arr.length); // prints 3 (indexes 0 through 2 were created)
The length property takes into consideration only those members of the array which names are indexes (like '1', '2', '3', ... ).
Arrays in JavaScript have numeric indexes only.
Use an object, which is essentially what you are doing above, setting properties on that array object.
array.length returns how many values are stored in the array. The first alert is returning the value of the position 'pollType'.
The reference guide I always use when needing help with javascript arrays is this page http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
I'd also read what it says under the heading Javascript Does Not Support Associative Arrays, as you may run into problems with this also.
var pollData = Array();
function test() {
pollData[0] = 2
alert(pollData[0]);
alert(pollData.length);
}
//[x] is the array position; hence ['polltype'] is causing issues
I want to use a variable as the index parameter in an array but for some reason it's coming up as "undefined" when I do it this way. Any ideas?
var object_number = [];
var x = 1;
function create_new_object()
{
object_number[x] = new happy_object();
x++;
}
Array indices start at zero in JavaScript. When x starts at 1, there's an undefined element in the first position of the array. Start at x=0 instead.
There's a better way to do this, however. Instead of manually keeping track of the last element in the list, you can just use Array.push() to add a new element onto the end.
var object_number = [];
function create_new_object()
{
object_number.push(new happy_object());
}
When you want to find out how many elements are in the array, use Array.length (or the number returned by Array.push()).
Further reference: Array # MDC.
your object_number is an empty array with no elements. Hence you are getting this error.
To add elements to array, you need to use push method.
object_number.push(new happy_object() );
Also you need to start your array index from 0 instead of 1. i.e. your x should be 0.
In addition to the previous answers:
Unlike "normal" languages (which use block-scope), javascript uses function-scope.
So be shure x exists in side your function-scope when you use it like that.
you can't mess with array keys too too much in js - if you want a more solid, definable relationship, you'll need to mimic an associative array by doing:
var object_number = {};
var x = 1;
function create_new_object() {
object_number[x] = new happy_object();
}
Also, I'd combine your var statements. Makes variable/function hoisting a bit clearer.
var object_number = {}
, x = 1;