0

I have two arrays. One is the pattern, which contains 12 months and second is fetched from api. Pattern:

[
    {
      total: 0,
      month_name: "Jan",
    },
    {
      total: 0,
      month_name: "Feb",
    },
    {
      total: 0,
      month_name: "Mar",
    },
    {
      total: 0,
      month_name: "Apr",
    },
...
  ]

fetched:

[
    {
        "total": 4,
        "month_name": "Mar"
    },
    {
        "total": 1,
        "month_name": "Apr"
    }
]

I want to compare fetched array to pattern, find matching "month_name" and update "total". Fetched array contains objects with months only when they are above 0.

LeeLenalee
  • 27,463
  • 6
  • 45
  • 69
Publius
  • 39
  • 6

3 Answers3

1

I'd suggest making a lookup table (totalByMonth) then you can just loop over the state and update each one by looking up the total in totalByMonth.

const state = [
  {total: 0, month_name: "Jan"},
  {total: 0, month_name: "Feb"},
  {total: 0, month_name: "Mar"},
  {total: 0, month_name: "Apr"}
];

const fetched = [
  {total: 4, month_name: "Mar"},
  {total: 1, month_name: "Apr"}
];

//build totalByMonth object
const totalByMonth = {};
for (let f of fetched) {
  totalByMonth[f.month_name] = f.total;
}

//update state
for (let s of state) {
  const total = totalByMonth[s.month_name];
  if (total) s.total = total;
}

console.log(state);
Rocky Sims
  • 3,523
  • 1
  • 14
  • 19
0

You can try this :

let result = months.map(month => {
    let matching_result = fetched.filter(f => f.month_name == month.month_name);
    return matching_result[0] ? {...month, total: matching_result[0].total}: month;
});

console.log(result);

//Output
// [
// {total: 0, month_name: 'Jan'},
// {total: 0, month_name: 'Feb'},
// {total: 4, month_name: 'Mar'},
// {total: 1, month_name: 'Apr'},
// ]
nem0z
  • 1,060
  • 1
  • 4
  • 17
  • It will return the same array to fetched array. Result have to contains every of 12 months with total equals to 0 unless fetched array with matched month total is grater than 0 – Publius Jun 23 '22 at 12:59
  • It return the pattern array updated with fetched values (as you can see on the output), try it ;) – nem0z Jun 23 '22 at 13:03
0

let pattern=[{total:0,month_name:"Jan"},{total:0,month_name:"Feb"},{total:0,month_name:"Mar"},{total:0,month_name:"Apr"}]

let fetched=[{total:4,month_name:"Mar"},{total:1,month_name:"Apr"}];

function updateTotal(pattern,fetched){
    fetched.forEach((e) => {
      let index = pattern.findIndex(p => p.month_name === e.month_name)
      if(index > -1){
        pattern[index].total = e.total
      }
    } )
 }

updateTotal(pattern,fetched)
console.log(pattern)
Alan Omar
  • 4,023
  • 1
  • 9
  • 20