1

I have an array comprising of the following data and I am using javascript to process the data

Portfolio, Value
["SFT_DEA_LXD", 17841.17]
["SFT_DEA_LXD", 69373.28]
["SFT_DEA_LXD", 28279.65]
["SFT_ISA_LXD", 10082.31]

I have run a following code to summate the values and group by Portfolio

    function groupBy(array, groups, value) {
    var result = [],
        hash = Object.create(null);

    array.forEach(function (a) {
        var keys = groups.map(function (i) { return a[i] }),
            key = keys.join('|');
        if (!hash[key]) {
            hash[key] = keys.concat(0);
            result.push(hash[key]);
        }
        hash[key][hash[key].length - 1] += +a[value];
    });
    return result;
}

result = groupBy(testArray, [0], 1);

testArray is

["SFT_DEA_LXD", 115494.1]
["SFT_ISA_LXD", 10082.31]

and I need to transpose the data to the following format

["SFT_DEA_LXD", "SFT_ISA_LXD"]
[115494.1, 10082.31]

Can you advise how I can change the array to the above format to pass the data to highcharts, with thanks.

Many Thanks for any help

Colin

Omkar76
  • 1,317
  • 1
  • 8
  • 22
colin
  • 65
  • 2
  • 12
  • 3
    Does this answer your question? [Transposing a 2D-array in JavaScript](https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript) – Lionel Rowe Sep 04 '20 at 17:51

3 Answers3

1
const testArray = [["SFT_DEA_LXD", 115494.1],
["SFT_ISA_LXD", 10082.31]];

const newArray = [];
const newArray1 = [];
testArray.forEach(item => {
    newArray.push(item[0]);
    newArray1.push(item[1]); 
});
const result = [newArray, newArray1];
Nitzy
  • 264
  • 1
  • 9
  • Hi Nitzy I have integrated the above code into my system and it does exactly what I require, all working now the highcharts are producing the grouped data. Best Regards Colin – colin Sep 04 '20 at 18:56
1

I don't understand what exactly you want to do but for transposing array its very simple and you can do it with a function or script like this

let transpose = function(arr){
  let m = arr.length;
  let n = arr[0].length;
  let f = [];
  let t = [];
  for (let j=0;j<n; j++){
    t = [];
    for (let i=0;i<m; i++){
      t.push(arr[i][j]);
    }
    f.push(t);
  }
  return f;
} 

let a = [["test1",125.1] , ["test2",542.2],["test3",2.2]];
let b = transpose(a);
console.log(a);
console.log(b);
  • Hi Sobhan Thanks for your response much appreciated, I will test the code later. Best Regards Colin – colin Sep 04 '20 at 18:55
1
const portfolios = testData.map(([portfolio]) => portfolio);
const values = testData.map(([, value]) => value);

It's as simple as that.

'use strict';

const testData = [
    ["SFT_DEA_LXD", 115494.1],
    ["SFT_ISA_LXD", 10082.31]
];

const portfolios = testData.map(([portfolio]) => portfolio);
const values = testData.map(([, value]) => value);

console.log(portfolios); [ 'SFT_DEA_LXD', 'SFT_ISA_LXD' ]
console.log(values); [ 115494.1, 10082.31 ]
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43