1

I'm preparing data for dataProvider using amchart to create stacked Column chart in JS like this https://www.amcharts.com/demos-v3/stacked-column-chart-v3/ but using only 2 values (plan and actual) in staked columns, i have the response of my service as its shown below, and i would like grouping data so i have to change input array:

inputArr = [{Value: 10}, 
            {Value: 25}, 
            {Value: 30},
            {Value: 37}
            {Value: 43}];

by this

newArr = [{Value1: 10, Value2: 25}, 
          {Value1: 30, Value2: 37},
          {Value1: 43, Value2: 0}];  

if there are odd numbers of elements in array so make Value2 is 0 when transforming.

Ddos_dev
  • 13
  • 1
  • 3

1 Answers1

1

You could create a function to make this conversion:

let inputArr = [{Value: 10}, 
            {Value: 25}, 
            {Value: 30},
            {Value: 37},
            {Value: 43}];
            
function pairValues(ary)
{
  let newAry = [];
  let obj;

  // Loop the inputted array and pair values
  ary.forEach((subObj)=>
  {
    if(obj)
    {
      obj.Value2 = subObj.Value;
      newAry.push(obj);
      obj = undefined;
    }
    else
    {
      obj = {};
      obj.Value1 = subObj.Value;
    }
  });

  // If the last obj has no pair, set Value2 to zero
  if (obj)
  {
    obj.Value2 = 0;
    newAry.push(obj);
  }
  return newAry; 
}
let outputArr = pairValues(inputArr);
console.log(outputArr);
Lonnie Best
  • 9,936
  • 10
  • 57
  • 97