I need to loop through a array of arrays and calculate the sum of each array. The Json is a kendo-ui chart series with arrays of x,y coordinates. I need to return the sum of the x,y values. linq.js or javascript will work. thanks
JSON
var =series = [{
"style":"smooth",
"color":"blue",
"data":[
[600,30000],
[800,60000],
[1100,100000]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
So for this example i would need to end up with this
var newSeries = [{
"style":"smooth",
"color":"blue",
"data":[
[30600],
[60800],
[101100]
],
"name":"Subject Property",
"removeByNames":[
["Product1"],
["Product2"],
["Product3"]
],
"$$hashKey":"object:30"
}]
for(var i=0;i<series[0].data.length;i++){
var val = series[0].data[i];
newSeries.data[i] = val[0] + val[1];
}
You can use loop and use reduce
var series = [{
...
}]
for (var i = 0; i < series.length; i++) {
for (var j = 0; j < series[i].data.length; j++) {
series[i].data[j] = series[i].data[j].reduce(function(p,c) {
return p + c;
});
}
}
Demo: http://jsfiddle.net/kv854c61/1/
you just need to loop the values in your data properties something like this..
for( var i - 0; i < series.length-1; i++){
for( var j - 0; j < series[i].data.length-1; i++){
var result = series[i].data[j][0] + series[i].data[j][1];
series[i].data[j] = result;
}
}
now it would make sense to add the new data array, so as not to overwrite
series[i].new_data[j] = result;
Array.map is quite useful in this case:
// extracts the data entries of each item in the series
var data = series.map(function(item){ return item["data"]; });
function sum(point) {
return point[0] + point[1];
// in case point is of arbitrary dimension use Array.reduce:
// return point.reduce(function(prev, cur){ return prev + cur; }, 0);
}
var sums = data.map(function(arr){
return arr.map(function(point){
return sum(point);
});
});
// sums now contains an array of array of sums
// e.g. [[30600,60800,101100]]
Related
Our array
This is the dynamic array,every data array have different number of elements.
how can i find index based average and then add final result to last index of the series array.
series[
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
]
Our try :
var data = [];
var sum = 0;
var newseries = {};
for (var i = 0; i < series.length; i++) {
for(var j= 0;j<(Math.max(series[i].data.length);j++){
var rmv_undified=series[i].data[j];
if(rmv_undified!=undefined){
sum+=parseFloat(rmv_undified)/series.length;
}
}
data.push(sum);
};
newseries.data = data;
series.push(newseries);
but i got result like this :
series[
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
{data:[7,17.33,3.66]}
// wrong result of above code working 1+2+3+5+10/3 = 7,6+9+10+6+10+6+5/3 = 17.33,2+5+4/3 = 3.66
]
I need result :
series[
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
{data:[3,5.33,5.66,3.66,6.66,2,1.66]} // index based average
]
Find the max length of all arrays first, then iterate through series and average nth item each iteration until n is max length.
let series = [
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
];
const maxl = [].reduce.call(series, (max, obj) => Math.max(obj.data.length, max), -1)
let avgs = [];
for (let i = 0; i < maxl; i++) {
let avg = [].reduce.call(series, (acc, n) => acc + (n.data[i] ? n.data[i] : 0), 0)/series.length;
avgs.push(avg);
}
series.push({data: avgs});
console.log(series);
You have to loop over j first, and for fixed j iterate over the different arrays in series.
Alternatively you can keep your code and change
sum+=
to
sum[j]+= and initialize this variable as an array. Then you have to push accordingly.
Try below solution. We have to iterate first through series array and then through each data array.
var series = [
{data:[1,2,3,5,10]},
{data:[6,9,10,6,10,6,5]},
{data:[2,5,4]},
];
var averageArray=[];
series.forEach(function(obj){
var sum=0;
obj.data.forEach(function(arrValue){
sum = sum + arrValue;
});
averageArray.push(sum/obj.data.length);
});
series.push({data:averageArray});
console.log(series)
First, find the max length of the data array. Then iterate through each item of the series array to find the average. punkr code
function avgMultipleArrary(arr) {
var len = arr.length;
var sum = 0;
var maxLen=arr[0].data.length;
var resultArray = [];
for(var i=0;i<len;i++){
arr.map(function(arrEle,index){
if (maxLen < arrEle.data.length) {
maxLen = arrEle.data.length;
}
})
}
for(var i=0;i<maxLen;i++){
arr.map(function(arrEle,index){
var data = arrEle.data;
if(data[i] !== undefined)
sum +=data[i];
})
var avg = Number((sum/len).toFixed(2));
resultArray.push(avg)
sum =0;
}
arr.push({data:resultArray});
return arr;
}
So I have this function where I've need to take out the evens and odds and put them into separate arrays but I need the evens array to print first rather than the odds.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[i & 1].push(numbersArray[i]);
}
return evensOdds;
}
If you want to split the number by their even and odd values, instead of using the index (i), determine the sub array to push into using the value - numbersArray[i] % 2.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
If you want to split them by even and odd indexes use (i + 1) % 2 to determine the sub array to push into:
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
function divider(numbersArray) {
var evensOdds = [[], []];
for (var i = 0; i < numbersArray.length; i++) {
evensOdds[(i + 1) % 2].push(numbersArray[i]);
}
return evensOdds;
}
console.log(divider(numbersArray));
Just for fun, a forEach version of the accepted answer.
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var even_odd = [ [], [] ];
numbersArray.forEach( e => even_odd[e%2].push(e) );
console.log(even_odd);
I want to write a function that takes an array such as:
var columns = ['distance', 'times', 'acceleration']
Then from this array, I want to generate something like this:
[{id: id_0, distance: 0, times: 0, acceleration: 0}, {id: id_1, distance: 1, times: 1, acceleration: 1}]
Notice that we have 2 objects here, but I want it to be whatever number I pass in to my parameter. Here is what I have:
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0, rowLen = rows.length; i < rowLen; i++) {
for (var n = 0; i < columns.length; n++) {
// not sure how to construct an object here from looping through my columns array
generatedData.push({
id: 'id_ + n',
// confused here
});
}
return generatedData;
}
}
This is the perfect place to dynamically create your own function. Try this:
function createArrayOfObjects(columns, count) {
var objectProps = new Array(columns.length);
for (var i = 0; i < columns.length; i++){
//":j" will be the variable j inside the dynamic function
objectProps[i] = columns[i] + ":j";
}
var funcBody = "var arr = new Array(count);" +
"for(var j = 0; j < count; j++){" +
"arr[j] = {" + objectProps.join(',') + "};" +
"}" +
"return arr;";
//Create a new function and call it with count as the parameter, returning the results
return new Function("count", funcBody)(count);
}
var count = 10;
var columns = ['distance', 'times', 'acceleration'];
createArrayOfObjects(columns.concat('id'), count);
This has the benefit of only having to loop over the columns array once where other solutions require nested loops.
JSPerf
I am giving you away the initial non-optimized solution. Its upto you to do the optimizations.
generateData: function(rows, columns) {
var generatedData = [];
for (var i = 0; i < rows.length; i++) {
var myObj = {};
myObj["id_" + i] = i;
for (var n = 0; n < columns.length; n++) {
myObj[columns[n]] = i;
}
generatedData.push(myObj);
}
return generatedData;
}
A functional approach that will take the object properties from the passed in array, instead of hard-coding them, might look something like this inside the for loop to populate an array named 'rows' with property names coming from the values of an array named 'cols':
cols.forEach(function(cv, ci, ca) { rows[ri][cv] = ri; });
See the snippet for a full example. Note that, in this example, I'm just shoving the current index of "rows" into the object as the property value.
var columns = ['distance', 'times', 'acceleration'];
function generateData(numRows, cols) {
rows = new Array(numRows);
for(ri=0; ri < rows.length; ri++) {
rows[ri] = { id: ri };
cols.forEach(function(cv, ci, ca) {
rows[ri][cv] = ri;
});
}
return rows;
}
data = generateData(5, columns);
console.log(data);
I want to convert array of array into array of key-value pairs using javascript or jquery.
i have array of array like :
var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
how do i convert arrOfarr into the array of key-value pairs that looks like
[{id:1,text:'One'},{id:2,text:'Two'},{id:3,text:'Three'}]
var result = [];
for (var i = 0, iLength = arrOfarr.length; i < iLength; i++) {
result.push({ id: arrOfarr[i][0], text: arrOfarr[i][1] });
}
console.log(result);
you can use $.map()
arrOfarr = jQuery.map(arrOfarr, function(val){
return {id: val[0], text: val[1]}
})
Demo: Fiddle
var arrOfarr = [[1,'One'],[2,'Two'],[3,'Three']];
var hash = new Array(arrOfarr.length);
for (var x = 0; x < hash.length; x++) {
hash[x] = {id: arrOfarr[x][0], text: arrOfarr[x][1]};
}
This might help you with performance if you have a large array or a lot of arrays because it'll allocate the size of the array in advance.
var result = [];
for(var i = 0; i < arrOfarr.length; i++){
var ar = arrOfarr[i];
result.push({ id: ar[0], text: ar[1] });
}
You can;
var arr = [[1,'One'],[2,'Two'],[3,'Three']];
var o = []
for (var i = 0; i < arr.length; i++)
{
o.push({id: arr[i][0], text: arr[i][1]});
}
try this,
a=[[1,'one'],[2,'two'],[3,'three']];
$.each(a,function(id,value){
a[id]={id:value[0],text:value[1]};
});
now a will have three objects as you want.
so what i have is three (or more) array with different sizes something like the following :
a ['x1' , 'x2', 'x3'];
b ['y1','y2']
c ['z1']
i want to create a string like the following :
x1,y1,z1 - x2,y2 - x3
any idea how the logic behind doing something like this?
Just because I like to be contrary (who'd a thunk it!), here's an alternative using plain for loops:
var data = [
['q1','q2'],
['x1', 'x2', 'x3'],
['y1', 'y2', 'y3', 'y4', 'y5'],
['z1']
];
var result = [];
for (var i=0, iLen=data.length; i<iLen; i++) {
temp = data[i];
for (var j=0, jLen=temp.length; j<jLen; j++) {
if (!result[j]) {
result.push([temp[j]]);
} else {
result[j].push(temp[j]);
}
}
}
alert(result.join(' - ')); // q1,x1,y1,z1 - q2,x2,y2 - x3,y3 - y4 - y5
If support for sparse arrays is required (i.e. with missing members or values of undefined or null or whatever), that's not too hard to implement.
var arrays = [a, b, c];
var groupings = [];
var idx = 0;
while (true) {
var items = [];
for (var i = 0; i < arrays.length; i++) {
if (arrays[i].length > idx) {
items.push(arrays[i][idx]);
}
}
if (!items.length)
break;
else
groupings.push(items.join(','));
idx++;
}
console.log(groupings.join(' - '));
Let's say you have an array of arrays of arbitrary number, then you can use code like this to iterate through them:
var data = [
['q1', 'q2'],
['x1', 'x2', 'x3'],
['y1', 'y2', 'y3', 'y4', 'y5'],
['z1']
];
var output = "";
var term, j = 0;
while (true) {
term = [];
for (var i = 0; i < data.length; i++) {
if (data[i].length > j) {
term.push(data[i][j]);
}
}
// if no more terms, then all arrays are exhausted
// so it's time to break out of the loop
if (term.length == 0) {
break;
}
if (output) {
output += " - ";
}
output += term.join(",");
j++;
}
alert(output);
And, a working example here: http://jsfiddle.net/jfriend00/fZKbp/