I am facing a little issue while inserting object data on specific index in Array.
Here is my JSON
let arr = [
{"days":3, "count" : 10 },
{"days":4, "count" : 12 },
{"days":7, "count" : 14 },
{"days":9, "count" : 20 }
]
Output, I would like to have.
updatedArr = [
{"days":0, "count" : 0 },
{"days":0, "count" : 0 },
{"days":3, "count" : 10 },
{"days":4, "count" : 12 },
{"days":0, "count" : 0 },
{"days":6, "count" : 34 },
]
so basically I want the object data to be pushed at specific index based on its key called days.
If the value of days is greater than 5 then it would be a sum of all the days value into one and push that at the last index e.g. 5th index.
Here is the code I have tried.
let arr = [{
"days": 3,
"count": 10
},
{
"days": 4,
"count": 12
},
{
"days": 7,
"count": 14
},
{
"days": 9,
"count": 20
}
]
for (let index = 0; index < 6; index++) {
const element = arr[index];
let eachObject = {}
eachObject.count = 0
if (element && element !== undefined && element.days && element.days <= 5) {
eachObject.days = element.days
eachObject.count = element.count
arr.splice((element.days - 1), 0, eachObject)
} else if (element && element !== undefined && element.days > 5) {
eachObject.days = element.days
eachObject.count += Number.parseInt(element.count)
arr.splice(4, 0, eachObject)
} else {
eachObject.days = 0
eachObject.count = 0
arr.push(eachObject)
}
}
Any help would be great.
Thank You.