Is this array with in array declaration correct? and if it is correct how can I output or atleast alert all the contents in the chkArray?
var chkArray = { tv_type[],screen_size[],connectivity[],features[]};
var tv_type = [];
var screen_size = [];
var connectivity = [];
var features = [];
Define array according variable scope
var tv_type = [];
var screen_size = [];
var connectivity = [];
var features = [];
//incorrect syntax
/*var chkArray = { tv_type[],screen_size[],connectivity[],features[]};*/
//change to
var chkArray = [tv_type,screen_size,connectivity,features];
For debug Try this
alert(JSON.stringify(chkArray))
OR
console.log(chkArray)
I think you want an object with arrays in it even though you are asking for arrays in array. It's more meaningful for your usecase. A bit like this
var chkArray = {
tv_type: [],
screen_size: [],
connectivity: [],
features: []
}
To access them you can say:
chkArray.tv_type[index]
And push items:
chkArray.tv_type.push("LCD");
You can not declare a multidimensional array like this
Possible solution will be
var arrayA = [];
var arrayB = [];
var arrayC = [];
var arrayTotal = [arrayA,arrayB,arrayC];
and you can use
console.log(arrayTotal)
to print the array in console
Related
I searched a lot, but I could not get a satisfactory answer on the net. In javascript, how do I add an array into another multidimensional array at a particular position based on a key value?
finalArray = []; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = [];
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp; // This gives an error
}
basically, I have
group = [ 'alpha' ,'beta', 'gamma' ]; //this array generated dynamically
my finalArray should be like,
finalArray['alpha'] = [ some records ];
finalArray['beta'] = [ some records ];
....
As far as I know, the way to add array into another array is to use .push() method, but that creates indices as 0, 1, 2... which is not desired. Please help me out
You have to use Object instead of Array. Make the following changes in the code
finalArray = {}; //final result to be stored here
for(var i=0; i<5; ++i)
{
var temp = {};
for(var j in $scope.team[i])
{
// counter = some value calculated here
temp[j] = $scope.team[i][j][counter];
}
finalArray[group[i]] = temp;
}
console.log(finalArray); //to see the object key value structure
now you can reference the values in finalArray with group[i] name. Hope this helps
You have to define your finalArray variable as Object instead of and Array:
var finalArray = {}; //or better in your case finalMap
var group = [ 'alpha' ,'beta', 'gamma' ];
var finalArray = {}; //declare it object as you dont want 0,1 indexes
for (var index in group){
finalArray[group[index]] = "some records/arry of records"
}
console.log(finalArray);
DEMO
I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo
I have a JSON associate array
[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
and I want to make it so that it becomes an array where
{
theatre = Test
time = 5:00pm
},
{
theatre = Testing2
time = 4:30 pm
}
But I can't figure out how to take a key name and make it a value...
Any help? I was looking at Object.keys but I couldn't find a suitable solution.
You have an array with object values. You'd need to loop over them:
var oldArray = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
var newArray = [];
for (var i = 0; i < oldArray.length; i++) {
var keys = Object.keys(oldArray[i]);
newArray.push({
theatre: keys[0],
time: oldArray[i][keys[0]]
});
}
http://jsfiddle.net/FNAtw/
This will give you an array stored in newArray with two elements. The first element is an object with kvps theatre: 'Test' and time: '5:00pm'. The second element is an object with kvps theatre: 'Testing2' and time: '4:30pm'.
Try this workaround:
var json = '[{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]';
var betterJson = json.replace('{"', '{"theatre":"').replace('":"','",time:"');
If the JSON is always as simple as above, then this should work. But it's brittle...
If you have a JS object, you could use Object.keys. That will work in the latest browsers.
You can also loop each item and just save the 1st item.
var result = [];
var str = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}];
for (var i = 0; i < str.length; i++) {
var obj = {};
foreach (var key in str[i]) {
obj.theatre = key;
obj.time = str[i][key];
}
result.push(obj);
}
May be a bit clunky, BUT should work cross-browser.
var js = [{"Test":"5:00pm"},{"Testing2":"4:30 pm"}]
var newJSON = []
for(var i = 0; i< js.length; i++) {
for( var key in js[i]) {
if(js[i].hasOwnProperty(key)) {
var tmpJS= {};
tmpJS['theater'] = key;
tmpJS['time'] = js[i][key];
newJSON.push(tmpJS);
}
}
}
I'm trying to create a 3 dimensional array dynamicall in javascript based on a flat array of objects. after looping through the array, the array seems empty. If I print while in the loop, it seems to work, but then it seems to be gone and I want to return this to the caller. Help ?
//init the 3d array ??
this.teams = [];
for(var i = 0; i < sportsStandings.length; i++) {
var item = sportsStandings[i];
if(!this.teams[item.league])
this.teams[item.league] = new Array();
if(!this.teams[item.league][item.division])
this.teams[item.league][item.division] = new Array();
this.teams[item.league][item.division][this.teams[item.league][item.division].length]
= new Team(item.teamName, item.wins, item.losses);
console.log(this.teams); //this prints properly, and i see the 3d array grow
}
console.log('second' + this.teams); //this prints nothing
I cleaned up the code a bit, there is a couple of other ways to write it.
this.teams = [];
var teams = this.teams;
for(var i = 0; i < sportsStandings.length; i++) {
var ss = sportsStandings[i],
league = ss.league,
division = ss.division,
teamName = ss.teamName,
wins = ss.wins,
losses = ss.losses;
if (!teams[league]) {
teams[league] = {};
teams[league][division] = [];
} else if (!teams[league][division]) {
teams[league][division] = [];
}
var newTeam = new Team(teamName, wins, losses);
teams[league][division].push(newTeam);
}
Is this possible?
So I need to have an array with a dynamic name and content what can be extended and accessed.
object = {};
var two = ['thing', 'thing2'];
for(one in two){
object[two[one]] = [];
}
If yes but not in this way, then how?
This is definitely doable, just make sure that the object owns the property and it's not inherited from higher up in the prototype chain:
object = {};
var two = ['thing', 'thing2'];
for..in:
for(var one in two){
if(two.hasOwnProperty(one))
object[two[one]] = [];
}
for:
for(var i = 0; i < two.length; i++)
object[two[i]] = [];
var object = {};
var props = 'thing thing2'.split(' ');
for (var i=0,len=props.length;i<len;++i){
object[props[i]] = [];
}