Home > Enterprise >  converting column-structured arrays into rows
converting column-structured arrays into rows

Time:01-14

I'm sorry for asking but every time when I need to do something like this I get so confused. Every time I get stuck with multiple loops and the final decision that I make looks scary.

Let's say you got an object like this one:

export interface Data {
    id: number;
    type: string;
}

and array of that object:

let data: Data[] = [
     { id: 1, type: 'one' },
     { id: 2, type: 'two' }
];

what is the easiest/safe way to create an array like this one:

arrdata = [
   [1, 2],
   ['one', 'two']
];

The idea is similar to converting column-structured data into rows:

1,2
1,2
1,2

1,1,1
2,2,2

CodePudding user response:

Create array of empty arrays, which number is equal to key count.
Then for each object in data we go through each key and push it into corresponding array.

const data = [
  { id: 1, type: "one" },
  { id: 2, type: "two" },
  { id: 3, type: "three" }
];

const keys = Object.keys(data[0]).sort();
const arrData = new Array(keys.length).fill(0).map((_) => []);
data.forEach((d) => keys.forEach((k, i) => arrData[i].push(d[k])));

console.log(arrData);

CodePudding user response:

You can use array.prototype.reduce like this

let data = [
     { id: 1, type: 'one' },
     { id: 2, type: 'two' }
];

const initialData = [[],[]]

const newData = data.reduce((acc, { id, type }) => {
  acc[0].push(id);
  acc[1].push(type);
  return acc;
}, initialData)

console.log(newData)

  • Related