Good day buddy, i'm trying to convert 3 arrays into 1 object. I need each months array length to be in accordance with another arrays length If some one has any idea how to solve it i would be appreciated too much. Thanks for your time and reading this, have a nice day!
Data:
const months = [
"March 2022",
"April 2022",
"May 2022",
"June 2022"
]
const values = [
[ "-50" ],
[ "-100", "350", "-111" ],
[ "201", "200" ],
[ "-290" ]
]
const categories = [
[ "Credit" ],
[ "Debt", "Salary", "Credit" ],
[ "Salary", "Salary" ],
[ "Investments" ]
]
This is expected result:
[
{
"name": "March 2022",
"series":
{
"name": "Credit" ,
"value": -50
}
},
{
"name": "April 2022",
"series": [
{
"name": "Debt",
"value": -100
},
{
"name": "Salary",
"value": 350
},
{
"name": "Credit",
"value": -111
}
]
},
{
"name": "May 2022",
"series": [
{
"name": "Salary",
"value": 201
},
{
"name": "Salary",
"value": 200
}
]
},
{
"name": "June 2022",
"series":
{
"name": "Investments",
"value": -290
}
}
]
All what i did in last days is this code, but it's not working, before for length of second elements it was working, but, when length of 3rd element increased they start staking together, and this is not all.. I'm using angular's service, and when navigating from 1 route to another their length by index[i] start staking (if manually refresh page by crtl+r it's working).. When firts call in first for loop of console.log(values[i].length) its length are [1, 3, 2, 1] which is correct, but at next call(while going thougth pages) length is [2, 6, 4, 2] and increasing with each call:
const months = [
"March 2022",
"April 2022",
"May 2022",
"June 2022"
]
const values = [
["-50"],
["-100", "350", "-111"],
["201", "200"],
["-290"]
]
const categories = [
["Credit"],
["Debt", "Salary", "Credit"],
["Salary", "Salary"],
["Investments"]
]
let result = [];
let subArray1 = [];
let subArray2 = [];
for (let i = 0; i < values.length; i++) {
// if 1 expense per month push to subArray1 => result
if (values[i].length == 1) {
subArray1.push([{
"name": categories[i],
"value": +values[i]
}])
} else {
for (let j = 0; j < values[i].length; j++) {
// if more then 1 expense per month push to subArray2 => subArray1 => result
subArray2.push({
"name": categories[i][j],
"value": +values[i][j]
});
};
subArray1.push(subArray2);
};
};
//combine all together
for (let i = 0; i < months.length; i++) {
result.push({
"name": months[i],
"series": subArray1[i]
});
};