I have an array that contains multiple objects and each object has an array called data that contains multiple data.
"datasets": [ { data: [1227.0, 698.4, 2903.1, 7280.2, 5447.9] }, { data: [302.0, 170.7, 592.2, 1293.6, 961.3] }, { data: [239.0, 275.5, 353.5, 478.0, 576.9] }, ... ]
For each data array that I have, how can I write a logic so that I store the values for each matching index into a new array data set. For example, I need to generate a new array which would only contains the values at index zero like so:
[1227.0, 302.0, 239.0]
and then another array which would contain the values at index one only
[698.4, 170.7, 275.5]
The desired output that I need is the following:
"result": [ { data: [1227.0, 302.0, 239.0] }, { data: [698.4, 170.7, 275.5] }, { data: [2903.1, 592.2, 353.5] }, { data: [7280.2, 1293.6, 478.0] }, { data: [5447.9, 961.3, 576.9] } ]
How will I achieve this. Can someone please help me out?
Advertisement
Answer
It looks like you need to transpose your data. Here’s one possible solution:
Assuming this was nested inside an object called dataset:
Ex:
const dataSet = { "datasets": [ { data: [1227.0, 698.4, 2903.1, 7280.2, 5447.9] }, { data: [302.0, 170.7, 592.2, 1293.6, 961.3] }, { data: [239.0, 275.5, 353.5, 478.0, 576.9] }, ... ] }
Now, this is a bit of a cumbersome process, but the solution would involve:
- Iterating through every element object of dataSet[“datasets”]
- Create a new array upon every increment of i
- Stopping at the jth element of dataSet[“datasets”][i].data[j] and store that it in the array instance
- When you’ve went through every object element’s jth position, push that array instance into an output array.
Here’s how one solution would look (O(n^2)) :
const matrixObjTranspose = (matrixObj) => { const output = []; for (let i = 0; i < matrixObj.datasets[0].data.length; i += 1) { const newSubArr = []; for (let j = 0; j < matrixObj.datasets.length; j += 1) { newSubArr.push(matrixObj.datasets[j].data[i]); } output.push(newSubArr); } return output; }; console.log(matrixObjTranspose(dataSet))