I need to create a new array of objects with 12 item (months & value) on it but it must check if the month exist on other array. If it exist it will push onto the array if not it will have a value of 0
Array to check with
arr1 =
[
{
date: 2024-02,
value: "100"
},
{
date: 2024-08,
person: "200"
},
]
What I did
const getMonthlyAmount = () => {
let arr = [];
for (i = 1; i <= 12; i++) {
arr1.map((item) => {
if (arr1.date.slice(0, 5) === i) {
arr.push(item);
}
});
}
return arr;
};
Result I want:
arr = [
{
date: 2024-01,
value: 0
},
{
date: 2024-02,
value: "100"
},
... continue
{
date: 2024-08,
person: "200"
},
... continue
{
date: 2024-12,
value: 0
},
]
2
Answers
You could do it like this:
This will create the "missing" month and set the value to 0 if they do not exist in the original array you provided.
Demo
You could collect the given date in an object and map a new array by ching the references or taking a new object.