Array data split - javascript

I don't know if i am doing the array add by a correct method.
for (var i=0; i < result.length; i++){
var a = Array();// loop against the Data array on each object in result
var b = Array();
a.push(result[i].data.mentionTotal);
b.push(result[i].profileName);
mentionArr.push(b+a);
}
The for loop above gave a result like this :
[["orange1494"],["ansontest231403"],["happyboy0"],["babygirl0"]]
But i want to split the data so i tried to do:
mentionArr.push(b+'","'+a);
In order to split it but the outcome is like :
["orange\",\"1494","ansontest23\",\"1403","happyboy\",\"0","babygirl\",\"0"]
Which i am not able to use this array to do my task.
How may i solve it to:
[["orange","1494"],["ansontest23","1403"],["happyboy","0"],["babygirl","0"]]

Use:
for (var i=0; i < result.length; i++){
var a = [];
a.push(result[i].data.mentionTotal);
a.push(result[i].profileName);
mentionArr.push(a);
}
You dont need to create two arrays. Everytime the for loop runs a will initialize as a new array.

You just need to replace one line (mentionArr.push(b+a); to mentionArr.push([b,a]);) so you generate a new array with a and b in it instead of concatinating the two values:
for (var i=0; i < result.length; i++){
var a = Array();// loop against the Data array on each object in result
var b = Array();
a.push(result[i].data.mentionTotal);
b.push(result[i].profileName);
mentionArr.push([b,a]);
}

Related

Javascript array with index and multiple items on it

I've to do a strange thing and I don't know if is possible.
Let assume I've one aray
MasterArray = [1,2,3,4];
Now for each MasterArray item I need to have multiple insertion, for example under the item 1 I've to push N value, for example the MasterArray[0] must have this correlations
5,8,3,9 ...
This for any items on MasterArray.
My first idea is to create a new array one for each MasterArray items, something like this
var newobject = X;
for (i = 0; i < MasterArray.length; i++) {
Arr[i] = push the newobject ;
}
But I don't think that is a good way!
The purpose it to have a kind of correlated array.
MasterArray[0] is correlated to another array [5,8,3,9, ...]
MasterArray[1] is correlated to another array [5,6,7,1, ...]
MasterArray[2] is correlated to another array [7,45,23,2, ...]
And so on
I hope to have explained myself
Just create a 2D array in this way:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = new Array(10);
}
Or, if you don't need to specify any size:
var myArray = new Array(5); // For example 5;
for (var i = 0; i < myArray.length; i++) {
myArray[i] = [];
}
EDIT:
For manipulate you just need to use innested loops:
for (var i = 0; i < myArray.length; i++) {
for (var j = 0; i < myArray[i].length; j++) {
myArray[i][j] = x; // where x is some variable
}
For add elements in the back just use .push() method:
myArray[0].push(5);

For loop withoit indexes javascript

I want to display an array without showing of indexes. The for loop returns the array indexes which is not showing in usual declaration.
I want to send an array like [1,2,3 ...] but after retrieving from for loop, I haven't the above format. How can I store my values as above.
var a = [];
for (var i = 1; i < 8; i++) {
a[i] = i;
};
console.log(a);
Outputs:
[1: 1, 2: 2 ...]
Desired output:
[1,2,3]// same as console.log([1,2,3])
Array indices start at zero, your loop starts at 1, with index 0 missing you have a sparse array that's why you get that output, you can use push to add values to an array without using the index.
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);
The problem is that you start your array with 1 index, making initial 0 position being empty (so called "hole" in array). Basically you treat array as normal object (which you can do of course but it defeats the purpose of array structure) - and because of this browser console.log decides to shows you keys, as it thinks that you want to see object keys as well as its values.
You need to push values to array:
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
I have to disagree with the answers provided here. The best way to do something like this is:
var a = new Array(7);
for (var i = 0; i < a.length; i++) {
a[i] = i + 1;
}
console.log(a);
Your code is making each index equal to i, so use it this way
var a = [];
for (var i = 1; i < 8; i++) {
a.push(i);
};
console.log(a);

take from a string specific values

Hello I want to take fro a string i javascript specific values , the string has this format
[
{
"st_asgeojson": "{\"type\":\"MultiLineString\",\"coordinates\":[[[23.4582348,37.5062675],[23.4577141,37.5066109],[23.4572601,37.5070038],[23.4566746,37.507301],[23.455698,37.5076256],[23.4549737,37.5079214],[23.4545445,37.5080235],[23.4538579,37.5078873],[23.4325504,37.5231202],[23.4324646,37.5234265],[23.4324646,37.5236308],[23.4326363,37.5237669]]]}"
},
{
"st_asgeojson": "{\"type\":\"MultiLineString\",\"coordinates\":[[[23.4568043,37.5042114],[23.4566078,37.5040436],[23.4567394,37.5038528],[23.4571075,37.5037422],[23.4575424,37.5035515],[23.4580841,37.5031548],[23.4589958,37.5027237]]]}"
}
]
from this string i want to make an new 2d array , in this array i want to put only the coordinates.
for example i want to have in first row the first st_asgeojson coordinates [23.4582348,37.5062675],....,[23.4326363,37.5237669] and the second row the other st_asgeojson coordinates [23.4568043,37.5042114],[23.4566078,37.5040436],......,[23.4589958,37.5027237].
Is this posible to do it ?
i try to str.split("[ ]") but is show me the same as the string i have first.
The original string is JSON, so you first have to convert it to an array with JSON.parse():
var arr = JSON.parse(str);
Then the value of the st_asgeojson property is another JSON-encoded object, so you'll have to parse that as well:
var first_coords = JSON.parse(arr[0].st_asgeojson).coordinates[0][0];
var second_coords = JSON.parse(arr[1].st_asgeojson).coordinates[0][0];
There's no [ ] anywhere in the string, so I'm not sure what you expected str.split('[ ]') to achieve. Did you mean to use a regexp, str.split(/ /) to split it on the spaces?
To get them all with a loop do:
var arrLeng = arr.length;
for (var i = 0; i < arrLeng; i++) {
var coordArray = JSON.parse(arr[i].st_asgeojson).coordinates;
var coordArrLeng = coordArray.length;
for (var j = 0; j < coordArrLeng; j++) {
var coords = coordArray[0][0];
var coordLeng = coords.length;
for (var k = 0; k < coordLeng; k++) {
alert(coords[k]);
}
}
}

Push is not a function JavaScript error

In the below code, I am getting "push is not a function" error. Can anyone please let me know what I am doing wrong here? I am trying to create 2D array in Javascript.
var myArray = new Array(4);
myArray = ["0","0","0","0"];
for (var i=0; i<myArray.length; i++) {
myArray[i].push("ID");
myArray[i] = new Array(1);
for (var j=0; j<myArray[i].length; i++) {
myArray[i][j].push("Array[j]");
}
}
Firebug is pointing me to:
myArray[i].push("ID");
For this line I am getting "TypeError: myArray[i].push is not a function"
Final array it should look like is:
[ID,"SomeValue1"],
[ID,"SomeValue2"],
[ID,"SomeValue3"]
And I cannot hard code, I need to create this dynamically based on data from DB
myArray[i].push("ID");
Is invalid of course because it's a function defined for an Array not for it's elements.
valid syntax would be
myArray.push("ID");
To know more about array.push() go here.
This will create your example.
var myArray = new Array(4);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", "SomeValue" + (i+1)];
}
But if you need to set data from a database, how is that being set in the Javascript? if it's in a different array you could do the following:
var dbArray = ["SomeValue1", "SomeValue2", "SomeValue3"];
var myArray = new Array(dbArray.length);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", dbArray[i]];
}
First of all, you can initialize Arrays using the Array Literal [] which should always be preferred
Then push is an Array method. So you have to call it on an Array
myArray[i] is the Element of the Array, myArray the Array
var arr = [];
for (var i = 0; i < 5;i++) {
arr.push = []; //Uses the Arrays push method
for ( var j = 0; j < 5; j++)
arr[i][j] = "Asd"; //Sets an Element
}
console.log(arr);
And as you see don't need to "Dim" an Array, you just can assign an Array to a Variable and start pushing Elements in it.
As you can see in the example, the first time
push is directly after arr, its the Arrays Method and appends a new Element to the Array
And in the second Example it accesses the Element and assigns it a value directly
What you are doing in your code is trying to invoke the push method on an Elements Array
Assume i is 0 Then
'myArray[i]' is "0" and the String "0" has no Method push.
But you can directly assing a new String to the Element like.
myArray[i] = "ID"

javascript declaring, and inserting to a multi-dimensional array

I now multi-dimensional array in javascript is a bit silly. But in my program I have to use it.
I want to declare a dynamic 3 columns and m-rows array using javascript and then in a loop i need to insert some element to that array. finally i want to display that array.
var x = new Array();
for (var y=0; y<=counter; y++) {
x[y] = new Array (3);
x[y][0]='a';
x[y][1]='b';
x[y][2]='c';
}
your help is highly appreciated ...
arrays grow as needed and so there is no point in declaring the length of the array. what you started with is fine.
http://books.google.ca/books?id=4RChxt67lvwC&pg=PA141&lpg=PA141&dq=JS+array+grow+as+needed?&source=bl&ots=tgY8BlGXm8&sig=_3jcH1LTmYi9QiXxn9pHROpbN1s&hl=en&sa=X&ei=7v60T_XwA4ThggfGuoEX&ved=0CEoQ6AEwAQ#v=onepage&q=JS%20array%20grow%20as%20needed%3F&f=false
http://www.codingforums.com/showthread.php?t=5198
just a heads up it will create an array that is 1 bigger then counter. this is b/c in your for loop you have y<=counter and y starting at 0. if you want the length to be counter change it to
y<counter
in order to display the array you might want to consider a for nested loop.
JS
for(var i=0; i<x.length; i++)
for (var j=0; j<3; j++)
alert(x[i][j]);
where x is the reference to the array.
if you want to print the entire array at once consider creating a string from the elements in the array and print that
function displayArray(x){
var stringArray='';
for(var i=0; i<x.length; i++)
for (var j=0; j<3; j++)
stringArray+= x[i][j];
alert(stringArray);
}
Something like this?
var x = [
[
[1, 2, 3],
[4,5,6]
],
[
[7, 8, 9]
]
];
alert(x[0][1][2]);
This is one reason why JavaScript's variable syntax isn't always what it's cracked up to be. Compare to Java:
String[][][] x = new String[5][5][5];
Something like this maybe?
var sDataArray=MultiDimensionalArray(7,2);
alert(sDataArray[0][0]);
function MultiDimensionalArray(iRows,iCols)
{
var i;
var j;
var a = new Array(iRows);
for (i=0; i < iRows; i++)
{
a[i] = new Array(iCols);
for (j=0; j < iCols; j++)
{
a[i][j] = "";
}
}
return(a);
}
Being dynamic in rows maybe you want a list of arrays? You can also do a method to add a line, and increase the array size.
try something like this..
var cols = 3;
var rows = 5;
createArray(cols,rows);
function createArray(cols,rows) {
var newArray = [];
for(i=0;i<cols;i++) {
newArray[i] = [];
for(j=0;j<rows;j++) {
newArray[i][j] = "["+i+"]"+"["+j+"]";
}
}
return newArray;
}

Categories

Resources