Loading two name / value arrays to a new object in Javascript - 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));

Related

How can I use data in a string to update a javascript object?

I have the following data array:
var ans =
[
{"text":"x","response":false},
{"text":"y","response":false},
{"text":"z","response":true}
];
var correct = "010"; // I need to add this to the array ans
Can anyone suggest how I could use use the data in the correct variable to add to the array so as to make:
var ans =
[
{"text":"x","response":false,"correct":false},
{"text":"y","response":false,"correct":true},
{"text":"z","response":true,"correct":false}
];
for(var i=0; i< ans.length; i++) {
ans[i].correct = correct.charAt(i) == "1";
}
for (var i = 0; i < correct.length; i++) {
ans[i]["correct"] = correct[i] === "1";
}
You an also do it like this(using a for-in loop).
Reference: For-each over an array in JavaScript?
for(key in ans){
ans[key].correct = correct.charAt(key) == "1";
}
var ans =
[
{"text":"x","response":false},
{"text":"y","response":false},
{"text":"z","response":true}
];
var correct = "010";
var sep = correct.split("");
var arr = [];
for (var i = 0; i < sep.length; i++) {
if (sep[i] == 0) {
arr.push("false");
} else {
arr.push("true");
}
}
var len = ans.length;
for (var i = 0; i < len; i++) {
ans[i].correct = arr[i];
}

Storing array object in a multidimentional array element in 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);

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

Javascript Array conversion [duplicate]

This question already has answers here:
Split array of objects into new arrays based on year of object's date
(3 answers)
Closed 9 years ago.
I was wondering how I could turn this:
var data = [
{id:1,option1:'short',option2:'red',option3:'gold'},
{id:2,option1:'short',option2:'red',option3:'silver'},
{id:3,option1:'short',option2:'blue',option3:'gold'},
{id:4,option1:'short',option2:'blue',option3:'silver'},
{id:5,option1:'long',option2:'red',option3:'gold'},
{id:6,option1:'long',option2:'red',option3:'silver'},
{id:7,option1:'long',option2:'blue',option3:'gold'},
{id:8,option1:'long',option2:'blue',option3:'silver'}]
Into something formatted like this using Jquery.
var new_data = {
short:{
red:{gold:1,silver:2},
blue:{gold:3,silver:4}
},
long:{
red:{gold:5,silver:6},
blue:{gold:7,silver:8}
}
}
That is easier than you might think. Try this:
function helper(obj,tree,value) {
for( var i=0, l=tree.length; i<l-1; i++) {
obj[tree[i]] = obj[tree[i]] || {};
obj = obj[tree[i]];
}
obj[tree[i]] = value;
}
var new_data = {}, l = data.length, i;
for( i=0; i<l; i++) {
helper(new_data,[data[i].option1,data[i].option2,data[i].option3],data[i].id);
}
This plain JS will do it:
var data = […];
var new_data = {};
for (var i=0; i<data.length; i++) {
var o = new_data;
for (var j=1; j<3; j++) {
var prop = data[i]["option"+j];
o = o[prop] || (o[prop] = {});
}
o[data[i]["option"+j]] = data[i].id;
}
But it looks easier to use that nested schema in the first place?
You can use .reduce() like this:
var new_data = data.reduce(function(res, obj) {
if (!res[obj.option1])
res[obj.option1] = {};
if (!res[obj.option1][obj.option2])
res[obj.option1][obj.option2] = {};
res[obj.option1][obj.option2][obj.option3] = obj.id;
return res;
}, {});
or like this:
var new_data = data.reduce(function(res, obj) {
var o = res;
for (var i = 1; i < 3; i++)
o = (o[obj["option" + i]] = o[obj["option" + i]] || {});
o[obj.option3] = obj.id;
return res;
}, {});

Categories

Resources