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
]
)
Related
I just started to learn Apps Script and I need to add some text to each value of an array. This code just puts the values in another column:
function getData() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Stocks");
var symbol = sheet1.getRange('A1:A7').getValues();
sheet1.getRange('C1:C7').setValues(symbol);
}
I want to add some text to the output, like this:
function getData() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet()
.getSheetByName("Stocks");
var symbol = sheet1.getRange('A1:A7').getValues();
sheet1.getRange('C1:C7').setValues(
'=GOOGLEFINANCE("FRA:' + symbol + ")'
);
}
But I know that this won't work. How do I add to each value being written?
use a loop to go through your array of values
function getData() {
var sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Stocks");
var symbol = sheet1.getRange('A1:A7').getValues();
var destRange = sheet1.getRange('C1:C7');
for (var i = 0; i < symbol.length; i++)
symbol[i][0] = '=GOOGLEFINANCE("FRA:' + symbol[i][0] + '")');
destRange.setFormulas(symbol);
}
As range A1:A7 and C1:C7 are of same widht and height you can use back that array to then use setFormulas(array) of course use this method if you only use once symbol array if not then declare an empty array befor your loop as so :
var resultArray = []
then inside your for loop do:
resultArray.push(['=GOOGLEFINANCE("FRA:' + symbol[i][0] + '")']);
then use outside the for loop setFormulas():
destRange.setFormulas(resultArray);
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 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...
My problem is I am trying to extract certain things from the url. I am currently using
window.location.href.substr()
to grab something like "/localhost:123/list/chart=2/view=1"
What i have now, is using the index positioning to grab the chart and view value.
var chart = window.location.href.substr(-8);
var view = window.location.href.substr(-1);
But the problem comes in with I have 10 or more charts. The positioning is messed up. Is there a way where you can ask the code to get the string between "chart=" and the closest "/"?
var str = "/localhost:123/list/chart=2/view=1";
var data = str.match(/\/chart=([0-9]+)\/view=([0-9]+)/);
var chart = data[1];
var view = data[2];
Of course you may want to add in some validation checks before using the outcome of the match.
Inspired by Paul S. I have written a function version of my answer:
function getPathVal(name)
{
var path = window.location.pathname;
var regx = new RegExp('(?:/|&|\\?)'+name+'='+'([^/&,]+)');
var data = path.match(regx);
return data[1] || null;
}
getPathVal('chart');//2
Function should work for fetching params from standard get parameter syntax in a URI, or the syntax in your example URI
Here's a way using String.prototype.indexOf
function getPathVar(key) {
var str = window.location.pathname,
i = str.indexOf('/' + key + '=') + key.length + 2,
j = str.indexOf('/', i);
if (i === key.length + 1) return '';
return str.slice(i, j);
}
// assuming current path as described in question
getPathVar('chart');
You could split your string up, with "/" as delimiter and then loop through the resulting array to find the desired parameters. That way you can easily extract all parameters automatically:
var x = "/localhost:123/list/chart=2/view=1";
var res = {};
var spl = x.split("/");
for (var i = 0; i < spl.length; i++) {
var part = spl[i];
var index = part.indexOf("=");
if (index > 0) {
res[part.substring(0, index)] = part.substring(index + 1);
}
}
console.log(res);
// res = { chart: 2, view: 1}
FIDDLE
i been reading for hours trying to make this work but i dont have much knowledge to do it.
I have this js code:
var username=$(this).attr("username");
It pull a list of users f.e (admin, test1, test2, test3)
and i needs to split it into another var like this:
var members = [
['admin'],
['test1'],
['test2'],
['test3'],
];
I tried a lot of codes but i cant make it work, thanks in advance!
To get an array of usernames:
var username = $(this).attr("username");
var members = username.split(',');
To get exactly what you've suggested you want (an array of arrays? - I don't think this is actually what you want):
var username = $(this).attr("username");
var membersArr = username.split(',');
var members = new Array();
for (var i = 0; i < membersArr.length; i++)
{
members[i] = [ membersArr[i] ];
}
To get "[test1]", "[test2]" etc:
var username = $(this).attr("username");
var members = username.split(',');
for (var i = 0; i < members.length; i++)
{
members[i] = '[' + members[i] + ']';
}
Update
To get the array of arrays,
var username=$(this).attr("username");
var membersArray= username.split(' ').map(function(username){
return [username];
})
//[["admin"],["test"],["test1"],["test2"]]
I've added a fiddle here