I have a string array variable called 'myAttachmentArray[]' which holds different figures like this:
[0] - 50000
[1] - 51010
[2] - 52000
[3] - 50010
And the array size is dependent on an int variable called 'squadNumbers'
What I want to do, is to place all the 'myAttachmentArray[]' into another string variable called 'currentAttachments', but with a ',' in between each array value.
So, currentAttachments would = 50000,51010,52000,50010 ...
The only problem is that the array size is dynamic, so I can't do:
currentAttachments = myAttachmentArray[0]+","+myAttachmentArray[1]...
So I tried a for loop:
for(var i = 0; i <= (squadNumbers - 1); i++){
currentAttachments = currentAttachments + myAttachmentArray[i] + ",";
}
But I still don't get what I want ...Please help
You need to use join
currentAttachments = myAttachmentArray.join(",");
If it's really an array, you can use join:
myAttachmentArray.length = squadNumbers;
var str = myAttachmentArray.join(",");
That makes sure the array length is the value from squadNumbers, and then uses join to join together those entries. Each entry will be turned into a string, then joined using the delimiter you specify.
(But why is the number of entries in squadNumbers rather than just in myAttachmentArray.length in the first place?)
Like this?
currentAttachments = myAttachmentArray.join(",")
Related
new to JS and I'm trying to append all the elements of an array to one string or element. I have tried a few different things but to no luck.
for (let i = 0; i < data.foodlist.length; i++) {
const foodlist_obj = data.foodlist.item[i];
console.log(foodlist_obj)
}
This returns a list like so:
Apple
Banana
Orange
Grapes
etc
But I would love to get the list to be like "Apple, Banana, Orange, Grapes, etc".
I have tried to use append and a few other options but cant seem to figure it out any help is appreciated
This returns a list like so:
It does not return a list. const foodlist_obj is a local variable within the for loop and as such it's being reset at every iteration. What is logged is a single string variable 5 times.
You need to declare the variable outside the loop as an array, then append to it.
const foodlist_obj = [];
for (let i = 0; i < data.foodlist.length; i++) {
foodlist_obj[foodlist_obj.length] = data.foodlist.item[i];
}
console.log(foodlist_obj)
Use Array#join to concatenate the items:
const data = {foodlist:['Apple', 'Banana', 'Orange', 'Grapes']}
const joined = data.foodlist.join(", ");
console.log(joined);
if you want to get them as string you can use toString() method
const foodlist_obj = data.foodlist.toString()
also you can use join() to replace comma separate with any other thing like new line
const foodlist_obj = data.foodlist.join("\n")
if you wants to get them as text with a special syntax you can create a variable called text and set it's type to string then add the array elements when loop
var text = "";
for (let i = 0; i < data.foodlist.length; i++) {
text += data.foodlist[i] + " item number("+i+")\n";
}
console.log(text)
if you get error that's will be of you because in your code you looping through data.foodlist but when you called the array you called him as data.foodlist.item[i] how do you called item property when you looping through data.foodlist you should call it like that data.foodlist[i] so check your array good first before loop
also you testing the foodlist_obj when you still loop and that's shouldn't give you something except one item in each iteration
also you used const to decalre your variable but const is unchangeable variable it's take just the first value assigned to it there's some cases when you can push items to const but you can't assign then add new items to const as text
I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0
I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);
I have a string containing many lines of the following format:
<word1><101>
<word2><102>
<word3><103>
I know how to load each line into an array cell using this:
var arrayOfStuff = stringOfStuff.split("\n");
But the above makes one array cell per line, I need a two-dimensional array.
Is there a way to do that using similar logic to the above without having to re-read and re-process the array. I know how to do it in two phases, but would rather do it all in one step.
Thanks in advance,
Cliff
It sounds like you're hoping for something like Python's list comprehension (e.g. [line.split(" ") for line in lines.split("\n")]), but Javascript has no such feature. The very simplest way to get the same result in Javascript is to use a loop:
var lines = lines.split("\n");
for (var i = 0; i < lines.length; i++) {
lines[i] = lines[i].split(" ");
// or alternatively, something more complex using regexes:
var match = /<([^>]+)><([^>]+)>/.exec(lines[i]);
lines[i] = [match[1], match[2]];
}
Not really. There are no native javascript functions that return a two-dimensional array.
If you wanted to parse a CSV for example, you can do
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n') // Normalize newlines
// Parse lines and dump them in parsedStuff.
.replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
Running
stringOfStuff = 'foo,bar\n\nbaz,boo,boo'
var parsedStuff = [];
stringOfStuff.replace(/\r\n/g, '\n')
.replace(/.*/g, function (_) { parsedStuff.push(_ ? _.split(/,/g)) : []; })
JSON.stringify(parsedStuff);
outputs
[["foo","bar"],[],["baz","boo","boo"]]
You can adjust the /,/ to suite whatever record separator you use.
I have a javascript that has custom indexes, I created them like so:
var rand = event.timeStamp; //jquery on click event object
freeze_array[rand] = month + ',' + model_name + ',' + activity;
To remove the above element I have this:
freeze_array.splice(rand, 1);
But this does not remove the element as I can see it in my firebug dom object viewer. Here is an example of the array:
My indexes are in the form: 1283519490632 - too long to be an integer that is required by the splice method?
Thanks all for any help
As you mentioned, the index argument must be an integer. Maybe you can use an object that holds indices as follows:
var lastIndex=0; // that shall be global...
var pointer = {};
....
pointer[rand] = lastIndex;
++lastIndex;
Then use it as follows:
freeze_array = freeze_array.splice(pointer[rand], 1);
Yes the index must be an integer. Your value is too large for a integer.
See at w3schools
index: Required. An integer that
specifies at what position to
add/remove elements
Try this:
delete freeze_array[ rand ];