score:0
Basically you can take Array#map()
for this task.
var data0 = [{ id: 'name1', value1: 5, value2: 13 }, { id: 'name2', value1: 2, value2: 5 }, { id: 'name3', value1: 4, value2: 6 }, { id: 'name4', value1: 3, value2: 7 }],
result = function (array) {
var sum1 = 0,
sum2 = 0,
r = array.map(function (a) {
sum1 += a.value1;
sum2 += a.value2;
return { id: '_' + a.id, value: a.value2 - a.value1 };
});
return [{ id: 'sum1', value: sum1 }].concat(r, { id: 'sum2', value: sum2 });
}(data0);
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
score:-1
There are many different ways to achieve the result you need. One of them is to use map
and reduce
functions on the array items. You can read more about map
and reduce
on MDN .
var data0 = [ {id: 'name1', value1: 5, value2: 13}, {id: 'name2', value1: 2, value2: 5}, {id: 'name3', value1: 4, value2: 6}, {id: 'name4', value1: 3, value2: 7} ];
// calculate `sum1` and `sum2` as the sums of `value1` and `value2` respectively
var sums = data0.reduce(function (sums, item) {
sums.sum1.value += item.value1;
sums.sum2.value += item.value2;
return sums;
}, {
sum1: {id: 'sum1', value: 0},
sum2: {id: 'sum2', value: 0}
});
// transform (map) the existing data and calculate `value` as a difference between `value2` and `value1`
var restOfData = data0.map(function (item) {
return {
id: item.id,
value: item.value2 - item.value1
};
});
// merge the obtained results into a single array
var data = [sums.sum1].concat(restOfData, [sums.sum2]);
document.write(JSON.stringify(data));
This code is even more readable if you're using ES2015 thanks to arrow functions and spread operator: http://codepen.io/mmiszy/pen/EKmmEy?editors=0010
score:0
data0 = [ {id: name1, value1: 5, value2: 13}, {id: name2, value1: 2, value2: 5}, {id: name3, value1: 4, value2: 6}, {id: name4, value1: 3, value2: 7} ];
var data = [];
var sum1 = 0;
var sum2 = 0;
for (i = 0; i < data0.length; i++) {
sum1 += data0[i].value1;
sum2 += data0[i].value2;
var diff = data0[i].value2 - data0[i].value1;
data.push({id: 'name' + (i+1) + '_', value: diff});
}
data.unshift({id: 'sum1', value: sum1});
data.push({id: 'sum2', value: sum2});
Array.push() adds after the last Item of the Array, Array.unshift() before the first Item.
score:1
Wasn't sure what your id's were to be as it looked like you were using variables. I converted them into strings in this case. Enjoy!
Code could have been compact but i thought this would make it more readable for you in future. Feel free to ask any further questions, happy to help!
var data = [
{
id: 'name1',
value1: 5,
value2: 13
},
{
id: 'name2',
value1: 2,
value2: 5
},
{
id: 'name3',
value1: 4,
value2: 6
},
{
id: 'name4',
value1: 3,
value2: 7
}
];
// Calculate sums
var value1Sum = 0;
var value2Sum = 0;
data.forEach(function(object) {
value1Sum += object.value1;
value2Sum += object.value2;
});
// Insert sums at front and back
data.unshift({
id: 'sum1',
value: value1Sum
});
data.push({
id: 'sum2',
value: value2Sum
});
// Calculate differences
data = data.map(function(object, idx) {
if (idx === 0 || idx === data.length - 1) {
return object;
}
return {
id: object.id + '_',
value: object.value2 - object.value1
};
});
Source: stackoverflow.com
Related Query
- How to create a new array using the data from the old one?
- How to update elements of an HTML that the elements are created using data from a CSV file?
- How to create d3 graph using data from Rails database
- D3 How to update the chart after selection from drop down menu with new data
- Edit the data in a pie chart rather than create a new one
- In a d3 scatterplot using data from a csv file, how do i draw lines connecting related points when the mouse is over a point?
- How do you call data from nested JSON array using d3?
- How to reshaping Data in Javascript from array to object without losing some of the data
- Using d3 - How do I select specific data from array to highlight when I click a button?
- How to update data on a page according to data from a CSV file instead of using fixed element data on the page?
- Reload data from a drop down box created by script without having to delete the element and create another one
- Understanding D3 data join using the new syntax - Array data is update but DOM not
- How to create histogram using D3.js and reading data from JSON
- How to create a multiseries line chart using data filtered from a csv file?
- How can i use the data from Hbase to visualize using d3.js
- How to get the data from given array of objects in d3.js
- How do I select one group of values from dataset to plot a linechart using D3.js and not the whole dataset
- How to Create/Show Multiple Iterations of Charts with the same data in One Area with Buttons using D3.js
- consolidating data from a json in a new array and drawing shapes with it using d3.js
- consolidating data from a json in a new array and drawing shapes with it using d3.js
- In d3, how to get the interpolated line data from a SVG line?
- How do I create a tree layout using JSON data in d3.v4 - without stratify()
- Can d3.js draw two scatterplots on the same graph using data from the same source?
- how to create labels for data in donut chart using d3.js
- How to create a choropleth of the world using d3?
- How to load data from an internal JSON array rather than from an external resource / file for a collapsible tree in d3.js?
- NVD3 - How to refresh the data function to product new data on click
- How to plot animated line chart using d3 while the data table is required to be updated every 1 second?
- How to create correlogram using D3 as in the example picture
- How to get the data from the c3.js
More Query from same tag
- Typescript class implementing interface with anonymous function
- Accurate pan and zoom to svg node
- No Data value with D3
- How to add text-based legend to D3.js chart
- D3.js Don't Overlapping line but linktext not show
- D3.js selection does not have enter or exit
- how to add dragend event on svg element
- c3js › value 0 aligned between Y and Y2
- D3JS Petals / Flower Chart. How to adapt to use data
- How to set a tooltip width dynamically?
- d3.js, attribute d: Expected number, “MNaN,NaNLNaN,NaN”
- Change which notation d3.format uses for the 'g' type
- d3 v4 error this.setAttribute is not a function
- Uniting two data frames
- Element no longer draggable after adding parameter to d3 drag behavior
- d3.js Pie Chart invalid <path> attribute
- D3 x-axis not showing any data (datetime)
- Dynamically project a Single County
- d3.js range of values for lab colour
- How to draw non-scalable text in SVG with Javascript?
- Aligning text to the left & Right of a circle depending on the data
- d3 data parse/convert (from long to wide)
- broken legend and tooltip in zoomable sunburst chart (D3.js)
- Trying to transition d3v4 linegraph data from one dataset to a dataset with a different scale
- How to make D3 line hidden from start?
- python: how to save dynamically rendered html web page code
- Getting Vega-Lite / D3 to Work in Nuxt.js
- I want create a graph with a button
- How to filter children based on whether the parent is filtered in D3?
- d3.js creating grid-styled bar chart