How do I split this string with Js? - javascript

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

Related

Javascript for loop within function not pushing to array

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
]
)

Javascript, adding multiple arrays to an array with a for loop

What is the best way to consolidate this code? As it is, it works perfectly, but it needs to go up to maybe 40-50 items long, so it needs to be shortened dramatically, (I assume, with a for loop).
I'm pretty much a novice when it comes to Javascript, and trying to add arrays to an array with a loop is confusing me immensely.
The "vac1.", "vac2." ...etc, variables are used later on in the code to add pointers onto a Google Maps map.
var x = count.count; // x = a value that changes (between 1 & 50)
if(x == 1){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location]
];
}
if(x == 2){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location]
];
}
if(x == 3){
locations = [
[vac1.vacancy_title, vac1.vacancy_latlng, vac1.vacancy_url, vac1.vacancy_location],
[vac2.vacancy_title, vac2.vacancy_latlng, vac2.vacancy_url, vac2.vacancy_location],
[vac3.vacancy_title, vac3.vacancy_latlng, vac3.vacancy_url, vac3.vacancy_location]
];
}
...etc etc...
I have tried using a for loop, but it doesn't work and I have no idea if I am anywhere close to figuring out how to do it correctly.
var x = count.count;
locations = [];
array = [];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
Any help or advice would be greatly appreciated!
Thank you.
You need to consider them as a string:
var x = 5;
locations = [];
array = [];
for (i = 1; i <= x; i++) {
array = ['vac'+i+'.vacancy_title', 'vac'+i+'.vacancy_latlng', 'vac'+i+'.vacancy_url', 'vac'+i+'.vacancy_location'];
locations.push(array);
}
console.log(locations);
Create an array vac and use your previous code :
var x = count.count;
locations = [],
array = [],
vac = [ /* vac1, vac2, ...., vacn */ ];
for (i = 0; i < x; i++) {
array = [vac[i].vacancy_title, vac[i].vacancy_latlng, vac[i].vacancy_url, vac[i].vacancy_location];
locations.push(array);
}
You could use eval for the variable name and build an new array with another array for the wanted keys.
Basically you should reorganize yor program to use a solution without eval. An array could help. It is made for iteration.
var x = count.count,
i,
keys = ['vacancy_title', 'vacancy_latlng', 'vacancy_url', 'vacancy_location'],
locations = [];
object;
for (i = 1; i <= x; i++) {
object = eval('vac' + i);
locations.push(keys.map(function (k) { return object[k]; }));
}
Group the vac* elements in an array and then use slice to cut out as many as you want, then use map to generate the result array:
var vacs = [vac1, vac2 /*, ...*/]; // group the vacs into one single array
var x = count.count; // x is the number of vacs to generate
var locations = vacs.slice(0, x).map(function(vac) { // slice (cut out) x elements from the arrays vacs then map the cut-out array into your result array
return [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
});
Because any global variable is a property of the global object :
var vac1 = "whatever";
console.lof(window.vac1); // => logs "whatever"
console.lof(window["vac1"]); // => accessed as an array, logs "whatever" too
You could use the global object and access it as an array to look for your vac1, vac2, vac3 variables :
var x = count.count, i;
locations = [],
array = [],
var globalObject = window; // or whatever the global object is for you
var vac; // this will be used to store your vac1, vac2, etc.
for (i = 0; i < x; i++) {
vac = globalObject["vac"+i]; // the "vac" + i variable read from the global object
if (vac !== undefined) {
array = [vac.vacancy_title, vac.vacancy_latlng, vac.vacancy_url, vac.vacancy_location];
locations.push(array);
}
}

TypeError listOfNames.split is not a function

I am very new to coding and javascript and working on a project at school. I am not into the answers as it does me know good to be given them. however, I am stuck at a part of my program and I am unable to go any further in my testing. wondered if someone could share a little insight as to why I would be getting typeError is not a function on the listOfNames.split(" "); area of my code as provided to me by the console. It is very frustrating that I cant seem to figure our why. Thank you in advance. Here is what I have so far.
var realNinjas = [
'Chuck Norris',
'Jackie Chan',
'Lucy Liu',
'Billy Blanks',
'Michelle Yeoh',
]
var createListOfObjects = function(listOfNames){
var nameList = listOfNames.split(" ");
var namesArr = [];
// var firstName = [];
// var lastname = [];
for (var i = 0; i < nameList.length; i++){
namesArr.push("firstName:" + nameList[0], " " + "lastName:" + nameList[1]);
}
return;
//OUTPUT: List of strings
}
var ninjaListOfObjects = createListOfObjects(realNinjas);
split is a method of type String, not of Array
Use split over each string in array within loop
var realNinjas = [
'Chuck Norris',
'Jackie Chan',
'Lucy Liu',
'Billy Blanks',
'Michelle Yeoh',
]
var createListOfObjects = function(listOfNames) {
var namesArr = [];
for (var i = 0; i < listOfNames.length; i++) {
var split = listOfNames[i].split(' ');
namesArr.push("firstName:" + split[0], " " + "lastName:" + split[1]);
}
return namesArr;
}
var ninjaListOfObjects = createListOfObjects(realNinjas);
console.log(ninjaListOfObjects);

Finding an object and returning it based on search criteria

I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}

Transform a string into array using javascript

I have a string like this:
string = "locations[0][street]=street&locations[0][street_no]=
34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
What must I do with this string so i can play with locations[][] as I wish?
You could write a parser:
var myStr = "locations[0][street]=street&locations[0][street_no]=34&locations[1][street]=AnotherStreet&locations[1][street_no]=43";
function parseArray(str) {
var arr = new Array();
var tmp = myStr.split('&');
var lastIdx;
for (var i = 0; i < tmp.length; i++) {
var parts = tmp[i].split('=');
var m = parts[0].match(/\[[\w]+\]/g);
var idx = m[0].substring(1, m[0].length - 1);
var key = m[1].substring(1, m[1].length - 1);
if (lastIdx != idx) {
lastIdx = idx;
arr.push({});
}
arr[idx * 1][key] = parts[1];
}
return arr;
}
var myArr = parseArray(myStr);
As Shadow wizard said, using split and eval seems to be the solution.
You need to initialize locations first, if you want to avoid an error.
stringArray=string.split("&");
for (var i=0;i<stringArray.length;i++){
eval(stringArray[i]);
}
However, you might need to pay attention to what street and street_no are.
As is, it will produce an error because street is not defined.
Edit: and you'll need to fully initialize locations with as many item as you'll have to avoid an error.

Categories