Storing array object in a multidimentional array element in javascript - javascript

I have a scenario in which i've to store array object in a array.My Javascript code is
var myArray= new Array(5,5);
for(dataIndex in data.data){
for(myIndex in data.data[dataIndex].myObject){
var xrow =data.data[dataIndex].myObject[myIndex].row;
var xcolumn =data.data[dataIndex].myObject[myIndex].column;
myarray[xrow][xcolumn] = data.data[dataIndex].myObject[myIndex];
}
}
but could not store any data object in the array.Can anyone help me out sort this?

It looks like you're coming from PHP, where an array is both a sequence of elements and/or key-value pairs? An array in javascript is just a sequence. (Actually, that's not 100% true, but it is for all intents and purposes.) What you want is an object. An object is a series of key value pairs. The keys and values can be any object, from a string to an array to a function.
var myObj = {};
// or assigning properties up front
var myOtherObj = {'foo': 'bar', 'baz': 12 };

My problem was not declaring and setting value for the javascript array.I was able to acheive it by this.
var YourArrayHere = new Array();
YourArrayHere.length = [first dimension array length here];
for(var count = 0; count < YourArrayHere.length; count++)
{
var TempSecondArray = new Array();
TempSecondArray.length = [sec dimension array length here];
YourArrayHere[count] = TempSecondArray;
}

Ok got a working demo. Took me a while to figure it out. Was fun. It can be optmized.
EDIT: you don't really need a MAX.
jsfiddle: http://jsfiddle.net/Grimbode/7B8CK/1/
var data = {
"data":[
{"myObject":[
{"row":0, "column":0},
{"row":0, "column":1},
{"row":0, "column":2},
]
},
{
"myObject":[
{"row":1, "column":0},
{"row":1, "column":1},
{"row":1, "column":2}
]
}
]
};
var result = new Array();
for(var i = 0; i < data.data.length; i++)
{
var temp = new Array();
var row = (data.data[i].myObject.length > 0) ? data.data[i].myObject[0].row: null;
for(var j = 0; j < data.data[i].myObject.length; j++)
{
console.log('row: ' + data.data[i].myObject[j].row + ', column: ' + data.data[i].myObject[j].column);
temp[data.data[i].myObject[j].column] = [data.data[i].myObject[j]];
}
if(row != null){ result[row] = temp;}
console.log(result);
}
console.log('Final:');
console.log(result);
jsfiddle: http://jsfiddle.net/Grimbode/7B8CK/
I represented data as best as I could to fit your example
var MAX_X = 10;
var MAX_Y = 10;
var data = {
"data":[
{"myObject":[
{"row":0, "column":0},
{"row":0, "column":1},
{"row":0, "column":2},
]
},
{
"myObject":[
{"row":1, "column":0},
{"row":1, "column":1},
{"row":1, "column":2}
]
}
]
};
var result = new Array(MAX_X);
for(var i = 0; i < data.data.length; i++)
{
var temp = new Array(MAX_Y);
var row = (data.data[i].myObject.length > 0) ? data.data[i].myObject[0].row: null;
for(var j = 0; j < data.data[i].myObject.length; j++)
{
console.log('row: ' + data.data[i].myObject[j].row + ', column: ' + data.data[i].myObject[j].column);
temp[data.data[i].myObject[j].column] = [data.data[i].myObject[j]];
}
if(row != null){ result[row] = temp;}
console.log(result);
}
console.log('Final:');
console.log(result);

Related

Loading two name / value arrays to a new object in Javascript

I'm attempting to take two arrays, a column header array:
cNames = ["Year","Count"]
And a data array:
mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143]
I would like to line the two arrays into a single like so:
[
{
Year: "2005",
Count: 50212
},
{
Year: "2006",
Count: 51520
},
{
Year: "2007",
Count: 52220
},
{
Year: "2008",
Count: 52143
}
]
I've tried to load with:
var data;
for (var i=0; i < mData.length; i++) {
for (var j=0; j < cNames.length; j++) {
data[cNames[j]]=mData[i];
}
}
. . . but I don't get the desired result. I'm sure I'm missing something simple here . . . Any help would be appreciated!
You could use reduce, and push to the array based on the length of the array containing the keys, that way it should work whith arrays with any number of keys and values (as long as it adds up)
var cNames = ["Year","Count"]
var mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143]
var arr = mData.reduce( (a,b,i) => {
if (i%cNames.length === 0)
a.push(mData.slice(i,cNames.length+i).reduce((c,d,j) => (c[cNames[j]] = d, c),{}));
return a;
}, []);
console.log(arr)
You do it in the following way
let cNames = ["Year","Count"];
let mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143];
let i = 0, result = [];
while(i < mData.length){
let temp = {};
for(let j=0; j<cNames.length; j++){
temp[cNames[j]] = mData[i+j];
}
result.push(temp);
i += cNames.length;
}
console.log(result);
Or another approach :)
var cNames = ["Year","Count"];
var mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143];
var output = [];
for (var i = 0; i < mData.length; i+=cNames.length) {
var obj = {};
for (var j = 0; j < cNames.length; j++) {
obj[cNames[j]] = mData[i + j];
}
output.push(obj);
}
console.log(output);
Here is the code, which does the job
cNames = ["Year","Count"];
mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143];
var combinedData = [];
var i = 0;
mData.forEach(function(value,index){
if(i%2==0)
{
var itemToPush = {};
itemToPush[cNames[0]] = value;
itemToPush[cNames[1]] = mData[index + 1];
combinedData.push(itemToPush);
}
i++;
});
console.log(combinedData);
var cNames = ["Year","Count"];
var mData = ["2005",50212,"2006",51520,"2007",52220,"2008",52143];
var data = [];
var no_of_attributes = cNames.length;
while(mData.length > 0)
{
var attribute_values = mData.splice(0,no_of_attributes);
var temp = {};
for(var i=0; i<no_of_attributes; i++) temp[cNames[i]] = attribute_values[i];
data.push(temp);
}
console.log(JSON.stringify(data));

Javascript array not getting modified

I have some JSON data in the "data" variable.
FORMAT :
{
"0" : {"names":"Pooja, Trivedi"},
"1" : {"names":"Pooja, Rooster"}
}
I need to implement a map so as to count the different names:
Pooja = 2
Trivedi = 1
Rooster = 1
Here is the implementation:
map = new Array();
data = jQuery.parseJSON(data); //convert JSON to object
for (var i = 0; i < data.length; i++) {
var names = data[i].names.split(','); //split the CSVs
for (var j = 0; j < names.length; j++) {
if (map[names[j].trim()] === undefined) {
map[names[j].trim()] = 1;
} else {
map[names[j].trim()]++;
}
}
console.log(map); //shows progressively filled arrays
}
console.log(map); //shows [], an empty array
Inside the loop, the map is updated.
However after the end of the i loop, all we have is an empty array.
How is this to be resolved?
First of all, you don't want to use for (var i = 0; i < data.length; i++) to traverse your data object, because a Javascript object doesn't have a length property like an array would. So, use a for (var i in data) instead, to traverse all the keys in the object.
This works:
var data = {
"0" : {"names":"Pooja, Trivedi"},
"1" : {"names":"Pooja, Rooster"}
}
var map = {};
for (var i in data) {
var names = data[i].names.split(',');
for (var j in names) {
var name = names[j].trim();
if (map[name]) {
map[name]++;
} else {
map[name] = 1;
}
}
console.log(map); //shows progressively filled arrays
}
console.log(map); //shows the full array
And you don't want to use an array as your map. You should instead use an object.
I like this version better:
var data = {
"0" : {"names":"Pooja, Trivedi"},
"1" : {"names":"Pooja, Rooster"}
};
var nameCounts = {};
for (var item in data) {
data[item].names.split(", ").forEach(function (name) {
if (name in nameCounts) {
nameCounts[name]++;
} else {
nameCounts[name] = 1;
}
});
}
console.log(nameCounts);

How can I split the below string into a 2dimensional-array:

How can I split the below string into a 2dimensional-array:
Customer::Europe|UK|Scotland|Product::Drinks|Water|
array:
[Customer][Europe]
[Customer][UK]
[Customer][Scotland]
[Product][Drinks]
[Product][Water]
Not sure how to create the array. Haven't coded in years, so be kind
hArray= [];
vArray= [];
var i = j = 0;
var count = hierarchy.search(/[:|]+/);
write(hierarchy);
while (count > 0) {
if (hierarchy.indexOf(":") < hierarchy.indexOf("|") || (hierarchy.indexOf(":") > 0 && hierarchy.indexOf("|") == -1) ) {
hArray[j] = hierarchy.substr(0,hierarchy.indexOf(":"));
hierarchy = hierarchy.slice(hierarchy.indexOf(":")+2);
count = hierarchy.search(/[:|]+/);
j++;
} else
if (hierarchy.indexOf("|") < hierarchy.indexOf(":") {
vArray[i] = hierarchy.substr(0,count);
hierarchy = hierarchy.slice(count+1);
count = hierarchy.search(/[:|]+/);
i++;
}
if (count == -1) break;
//create multiArray ?
}
var source = "Customer::Europe|UK|Scotland|Product::Drinks|Water|";
var parts = source.split(/(\w+::)/);
var result = [];
for (var i = 1; i < parts.length; i += 2) {
var key = parts[i].replace("::", "");
var values = parts[i + 1].split("|");
for (var j = 0; j < values.length - 1; ++j) {
var line = new Array(2);
line[0] = key;
line[1] = values[j];
result.push(line);
}
}
console.log(result);
You can use Array.reduce like this. First, we split on | that is behind any owrd followed by ::. Then we reduce it, by using an array as memo and push an array into the memo, which we finally return.
var arr = input.split(/\|(?=\w+::)/).reduce(function(arr, str){
var array = str.split('::');
return arr.push(str.split('::')[1].split('|').filter(String).map(function(s){
return [array[0], s]
})), arr;
}, []);

javascript/jquery build array from counted array

Hey i have a simple question i cant find an answer,
i´m trying to generate some raw-data for a chart
lets say i have an array like :
[1,0,0,1,2,0]
is there a way to make an array out of it that has nested arrays that represent the count of duplicate entrys ?
[[0,3],[1,2],[2,1]]
here is some code that does the trick, but saves the count as objects
var array = [1,0,0,1,2,0];
var length = array.length;
var objectCounter = {};
for (i = 0; i < length; i++) {
var currentMemboerOfArrayKey = JSON.stringify(array[i]);
var currentMemboerOfArrayValue = array[i];
if (objectCounter[currentMemboerOfArrayKey] === undefined){
objectCounter[currentMemboerOfArrayKey] = 1;
}else{
objectCounter[currentMemboerOfArrayKey]++;
}
}
but objectCounter returns them like
{0:3,1:2,2:1}
but i need it as an array i specified above ?
for any help, thanks in advance
Try
var array = [1, 0, 0, 1, 2, 0];
function counter(array) {
var counter = [],
map = {}, length = array.length;
$.each(array, function (i, val) {
var arr = map[val];
if (!arr) {
map[val] = arr = [val, 0];
counter.push(arr);
}
arr[1] += 1;
})
return counter;
}
console.log(JSON.stringify(counter(array)))
Demo: Fiddle
You can turn your object into an array easily:
var obj = {0:3,1:2,2:1};
var arr = [];
for (var key in obj) {
// optional check against Object.prototype changes
if (obj.hasOwnProperty(key)) {
arr.push([+key, obj[key]]);
}
}
Note: The object keys are strings, so i converted them back to numbers when placed in the array.
Functional way of doing this, with Array.reduce and Array.map
var data = [1,0,0,1,2,0];
var result = data.reduce(function(counts, current) {
counts[current] = current in counts ? counts[current] + 1: 1;
return counts;
}, {});
result = Object.keys(result).map(function(current){
return [parseInt(current), result[current]];
});
console.log(result);
Output
[ [ 0, 3 ], [ 1, 2 ], [ 2, 1 ] ]
Try:
var data = [1,0,0,1,2,0];
var len = data.length;
var ndata = [];
for(var i=0;i<len;i++){
var count = 0;
for(var j=i+1;j<len;j++){
if(data[i] == data[i]){
count ++;
}
}
var a = [];
a.push(data[i]);
a.push(count);
ndata.push(a);
}
console.log(ndata)
DEMO here.
First you need to map the array to an associative object
var arr = [1,0,0,1,2,0];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] == undefined) {
obj[arr[i]] = 0;
}
obj[arr[i]] += 1;
}
Then you can easily turn that object into a 2d matrix like so:
arr = [];
for (var k in obj) {
arr.push([k, obj[k]]);
}
alert(JSON.stringify(arr));
Your existing object can be turned into an array with a simple for..in loop. Also your existing code that produces that object can be simplified. Encapsulate both parts in a function and you get something like this:
function countArrayValues(array) {
var counter = {},
result = [];
for (var i = 0, len = array.length; i < len; i++)
if (array[i] in counter)
counter[array[i]]++;
else
counter[array[i]] = 1;
for (i in counter)
result.push([+i, counter[i]]);
return result;
}
console.log( countArrayValues([1,0,0,1,2,0]) );
Demo: http://jsfiddle.net/hxRz2/

How do I merge a list of results into a compacted object with totals

I'm looping through a set of inputs. I need to tally up the grouped totals.
var compoundedArray = new Array();
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
var localObj = {};
localObj[dataType] = val;
compoundedArray.push(localObj);
});
I have an object like this
[
{
"growth":30
},
{
"growth": 40
},
{
"other": 20
}
]
how do I loop through the object to produce something like
[
{
"growth": 70
},
{
"other": 20
}
]
if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}
how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
I think your selection of data structure is a bit too complicated. Try something like.
var compoundedObject = {};
holder.find(".dataset input").each(function(index) {
var val = $(this).val();
var dataType = $(this).data("type");
//Assuming all values are integers and can be summed:
if( compoundedObject.hasOwnProperty(dataType) )
{
compoundedObject[dataType] += val;
}
else
{
compoundedObject[dataType] = val;
}
});
You will end up with an object, not an array though.
var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};
$.each(input,function(i,o){
var n;
for(i in o)
{n=i;break}
temp[n]=add(temp[n],o[n]);
});
$.each(temp,function(i,o){
var k={};
k[i]=o;
output.push(k)
});
find output at output variable.
Do not post much specific question, It might not help others.
This works. And it's pure javascript.
var totals = {};
for (var i = 0; i < compoundedArray.length; i++) {
var item = compoundedArray[i];
for (var key in item) {
totals[key] = (totals[key] || 0) + item[key]
}
};
You can loop trough an Object with a for loop.
If you want to delete an item simply set it to null.
Example:
for(var i in compoundedArray){
for(var j in compoundedArray){
if(i == j){
compoundedArray[i] += compoundedArray[j];
compoundedArray[j] = null;
}
}
}
You can do the following:
var totals = [], tmp = {};
for (var i = 0; i < compoundedArray.length; i++) {
var obj = compoundedArray[i];
for (var j in obj) {
tmp[j] = tmp[j] || 0;
tmp[j] += obj[j];
}
}
for(var k in tmp) {
var obj = {};
obj[k] = tmp[k];
totals.push(obj);
}
See this working demo

Categories

Resources