I am using multi dimension array to store data. It working but when we print it in console it show blank array and under it its showing two array, it should be show only one array inside.
It should look like this.
ar['outbound']['Meal']="111,121"
and its look in console like this
It is printing undefined also and one more thing
how to remove "," from the last
Here is fiddle
Code
var ar = [];
ar['Outbound'] = [];
ar['Inbound'] = [];
var ch="";
var sr= [];
sr['Meal']= [];
sr['Lounge']= [];
$('a').click(function(){
ch = $(this).parent().find('.no').text();
var boundType= $(this).parent().find('.bound').text();
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ","; console.log(ar)
})
To avoid "undefined" you have to set a default value to your array items:
if (!ar[boundType][service]) {
ar[boundType][service] = '';
}
And it's better to add ',' before adding a new value:
if (ar[boundType][service].length > 0) {
ar[boundType][service] += ',';
}
See demo: http://jsfiddle.net/AVU54/1/
The problem is here:
ar[boundType][$(this).parent().find('.service').text()] +=($(this).parent().find('.no').text()) + ",";
Replace that with:
var temp = $(this).parent().find('.service').text();
ar[boundType][temp] = (ar[boundType][temp] + "," || '') + ($(this).parent().find('.no').text());
This checks if the variable exists.
Also, arrays can't have strings as indexes. Use objects, instead:
var ar = {};
ar['Outbound'] = {};
ar['Inbound'] = {};
// etc...
Related
EDIT - code to calculate refill_playlist_len included
I have a function in Javascript that deletes a row of an HTML table and populates it again with values from arrays.
Within this deleteRow function, I have a for loop which loops through a string and assigns parts of the strings to different variables and tries to push them onto arrays.
Without the for loop, it works fine (i.e. when I just index manually) but for some reason when I place it in a for loop, the values aren't pushed onto the arrays. The values themselves print fine on each iteration they just aren't added to the array.
Refill_playlist_len is the count of the Django Queryset (30).
var refill_playlist_len = '{{ playlist.count }}';
var artist_Arr = [];
var track_Arr = [];
var track_id_Arr = [];
var album_Arr = [];
var artist_name;
var track_name;
var track_id;
var album_name;
for (var i = 0; i < refill_playlist_len; i++) {
var searchStr = refill_playlist[i];
console.log(searchStr);
console.log(typeof searchStr);
console.log(typeof refill_playlist);
//grab variables
artist_name = searchStr.match(new RegExp("artist_name:" + "(.*)" + ", album_name:"));
console.log(artist_name[1]);
artist_Arr.push(artist_name[1]);
track_name = searchStr.match(new RegExp("track_name:" + "(.*)" + ", acousticness:"));
console.log(track_name[1]);
track_Arr.push(track_name[1]);
track_id = searchStr.match(new RegExp("track_id:" + "(.*)" + ", track_name:"));
console.log(track_id[1]);
track_id_Arr.push(track_id[1]);
album_name = searchStr.match(new RegExp("album_name:" + "(.*)" + ", track_number:"));
console.log(album_name[1]);
album_Arr.push(album_name[1]);
}
The console logs are in the image below. You can see part of the 'searchStr' printed, along with the data types, artist name, track IDs, etc but for some reason, it says that 'searchStr' is undefined?
Console
I'm quite new to Javascript so my apologies if there is something basic I'm forgetting.
Multiple issues with code. Please clean up code. Sample is given below.
function find(refill_playlist) {
const refill_playlist_len = refill_playlist.length
let artist_Arr = []
let track_id_Arr = []
let track_Arr = []
let album_Arr = []
for (i = 0; i < refill_playlist_len; i++) {
var searchStr = refill_playlist[i];
if(!searchStr) continue;
//grab variables
artist_name = searchStr.match(/artist_name:(.*), album_name:/);
artist_name && artist_Arr.push(artist_name[1]);
track_name = searchStr.match(/track_name:(.*), acousticness:/);
track_name && track_Arr.push(track_name[1]);
track_id = searchStr.match(/track_id:(.*), track_name:/);
track_id && track_id_Arr.push(track_id[1]);
album_name = searchStr.match(/album_name:(.*), track_number:/);
album_name && album_Arr.push(album_name[1]);
}
console.log(artist_Arr)
console.log(track_id_Arr)
console.log(track_Arr)
console.log(album_Arr)
}
find(
[
`
artist_name: test, album_name:
`,
null
]
)
After an hour googling around I'm utterly confused about how to create & manipulate an associative array (I know it's actually an object) in JS. I'm trying to build an associative array / object as I loop through my page's elements thus:
var array_modules = {};
$('.module').each(function() {
var this_element = $(this);
var module_top = this_element.data('top');
var module_bottom = this_element.data('bottom');
array_modules.push({'top': module_top, 'bottom': module_bottom});
});
And somewhere else I'd like to retrieve the content of my array thus:
for (var index in array_modules) {
var top = array_modules['top'];
var bottom = array_modules['bottom'];
alert('top = ' + top + ' and bottom = ' + bottom);
}
None of this works though. What am I doing wrong?
you can push data into an array only. I hope the below code works for you.
var array_modules = [];
$('.module').each(function() {
var this_element = $(this);
var module_top = this_element.data('top');
var module_bottom = this_element.data('bottom');
array_modules.push({'top': module_top, 'bottom': module_bottom});
});
for (var index in array_modules) {
var top = array_modules[index]['top'];
var bottom = array_modules[index]['bottom'];
alert('top = ' + top + ' and bottom = ' + bottom);
}
This creates a array of associative objects
On your first part of code you are using array_modules as just an array and not associative, just use array_modules = []; On second part you are iterating an associative array but it should be array_modules[index]['top']. Still, by just changing to array just make a forEach loop.
Anyway, this is what I would do :
var array_modules = [];
$('.module').each(function() {
array_modules.push($(this).data());
});
array_modules.forEach(function(data){
console.log(data.top, data.bottom);
})
I am new for javascript, I have a one long string i want to split after 3rd commas and change diffferent format. If you are not understand my issues. Please see below example
My string:
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
I want output like this:(Each item should be in next line)
Idly(3 Pcs) - 10 = 200
Ghee Podi Idly - 10 = 300
How to change like this using JavaScript?
Just copy and paste it. Function is more dynamic.
Example Data
var testData = "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
Function
function writeData(data){
data = data.split(',');
var tempLine='';
for(var i=0; i<data.length/3; i++) {
tempLine += data[i*3+1] + ' - ' + data[i*3] + ' = ' + data[i*3+2] + '\n';
}
alert(tempLine);
return tempLine;
}
Usage
writeData(testData);
Use split method to transform the string in a array and chunk from lodash or underscore to separate the array in parts of 3.
// A custom chunk method from here -> http://stackoverflow.com/questions/8495687/split-array-into-chunks
Object.defineProperty(Array.prototype, 'chunk_inefficient', {
value: function(chunkSize) {
var array=this;
return [].concat.apply([],
array.map(function(elem,i) {
return i%chunkSize ? [] : [array.slice(i,i+chunkSize)];
})
);
}
});
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var arr = test.split(',');
var arr = arr.chunk_inefficient(3);
arr.forEach(function (item) {
console.log(item[1]+' - '+item[0]+' = '+item[2]);
});
You can use split to split the string on every comma. The next step is to iterate over the elements, put the current element into a buffer and flush the buffer if it's size is three. So it's something like:
var tokens = test.split(",");
var buffer = [];
for (var i = 0; i < tokens.length; i++) {
buffer.push(tokens[i]);
if (buffer.length==3) {
// process buffer here
buffer = [];
}
}
If you have fix this string you can use it otherwise validate string.
var test= "10,Idly(3 Pcs),200,10,Ghee Podi Idly,300";
var test2= test.split(",");
var temp_Str= test2[1]+' - '+test2[0]+' = '+test2[2]+'\n';
temp_Str+= test2[4]+'-'+test2[3]+' = '+test2[5];
alert(temp_Str);
I have been trying to use JavaScript array to push my object by header
like this :
var tab_temp = new Y.TabView(
{ srcNode: '#' + tabId }
);
tabsArray['"' + type + "_" + subTypes + '"'] = tab_temp;
Let's type = "x" and subTypes = "y", so I was expecting the object when I write something like:
tabs["x_y"]
But there is problem with this. When I debug, I can see this array will hold an object "x_y" but length of the array is 0
I can't use push also because in that way I need to use index to get it back but it is tough since sequence might change.
Edit 1:
I am using this because I want to hold a couple of TabView objects. Otherwise I can't reach those object after they created. (AlloyUI). I was able to push those object inside of array. As you see "Baru_BARANG" include and object that start with: s
Edit 2:
Thanks for help, I fixed it. I used Object instead of Array for this:
var tabs = {}
tabs[x + "_" + y] = "z";
I get the value by tabs[x + "_" + y]
You really need to be reading more about working with objects in JavaScript.
Try here first.
var type = "x";
var subType = "y";
var tabsArray = {};
tabsArray[type + "_" + subType] = "z";
console.log("tabsArray = ");
console.log(tabsArray);
console.log("tabsArray['x_y'] = " + tabsArray["x_y"]); // output: z
// Including code added to question as a comment:
var tabsArray = [];
var x = "x";
var y = "y";
tabsArray[x + "_" + y] = "z";
console.log("tabsArray['x_y'] = " + tabsArray["x_y"]);
// tabsArray.length will still be 0. To set .length you can use:
for (var i = 0; i < tabsArray.length; i++) {
tabsArray.length = ++i;
};
console.log("tabsArray.length = " + tabsArray.length);
You are most likely instantiating tabsArray as an array, i.e. var tabsArray = [];. This results in the observed behavior.
Since you want to define the keys yourself, you should instantiate it as an object instead:
var tabsArray = {};
tabsArray['x_y'] = 'z';
More about working with objects in JavaScript.
friends.
I have an array and it contains some string values.
ex: array name="All_array"
Now i want to check all values in that array for first character of a string.
if a String starts with character 'a' then move that string to array called "A_array".
if a String starts with character 'b' then move that string to array called "B_array".
How to achieve this task.
var splitArrays = {};
for(var i = 0; i < All_array.length; ++i){
var firstChar = All_array[i].substr(0,1).toUpperCase();
if(!splitArrays[firstChar + '_array'])
splitArrays[firstChar + '_array'] = [];
splitArrays[firstChar + '_array'].push(All_array[i]);
}
This will take every element in All_array and put them into an object containing the arrays indexed by the first letter of the elements in All_array, like this:
splitArrays.A_array = ['Abcd','Anej','Aali']
etc...
Here's a fiddle: http://jsfiddle.net/svjJ9/
The code would be this:
for(var i=0; i<All_array.length; i++){
var firstChar = All_array[i].substr(0, 1).toUpperCase();
var arrayName = firstChar + "_array";
if(typeof(window[arrayName]) == 'undefined') window[arrayName] = []; //Create the var if it doesn't exist
window[arrayName].push(All_array[i]);
}
A_array = []; //empty the array (cause you wanted to 'move')
Hope this helps. Cheers
You could do it using each() and charAt:
$.each(All_array,function(i,s){
var c = s.charAt(0).toUpperCase();
if(!window[c + '_array']) window[c + '_array'] = [];
window[c + '_array'].push(s);
});