skip to Main Content

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


  1. You could do it like this:

    const getMonthlyAmount = () => {
      return Array.from({ length: 12 }, (_, i) => {
        const month = (i + 1).toString().padStart(2, '0');
        const date = `2024-${month}`;
    
        const foundItem = arr1.find((entry) => entry.date === date);
        
        return foundItem ? foundItem : { date, value: 0 };
      });
    };
    

    This will create the "missing" month and set the value to 0 if they do not exist in the original array you provided.

    Demo

    const arr1 = [
      {
        date: "2024-02",
        value: "100"
      },
      {
        date: "2024-08",
        person: "200"
      },
    ];
    
    const getMonthlyAmount = () => {
      return Array.from({ length: 12 }, (_, i) => {
        const month = (i + 1).toString().padStart(2, '0');
        const date = `2024-${month}`;
    
        const foundItem = arr1.find((entry) => entry.date === date);
        
        return foundItem ? foundItem : { date, value: 0 };
      });
    };
    
    console.log(getMonthlyAmount());
    Login or Signup to reply.
  2. You could collect the given date in an object and map a new array by ching the references or taking a new object.

    const
        data = [{ date: "2024-02", value: "100" }, { date: "2024-08", person: "200" }],
        references = Object.fromEntries(data.map(o => [o.date, o])),
        result = Array.from({ length: 12 }, (_, i) => {
            const date = `2024-${(i + 1).toString().padStart(2, 0)}`;
            return references[date] || { date, person: 0 };
        });
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search