javascriptarraysalgorithmfindlookup

Create an array using item from different array


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 
 },
]

Solution

  • 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());