Home > Software engineering >  How to add value of missing object after comparing to another array?
How to add value of missing object after comparing to another array?

Time:11-12

I have an array of months (var months), and I am trying to filter out and get the months that the array of object (var array1) does not have and add empty value of property Avg

var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

var array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20},
{Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}];`

Eg. array1 has the property value of Month: Jan, Feb, May and Jun, but I want to get the months that are missing and add value of 0 to property Avg like {Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, ... for the missing months comparing it with months array

Expected result of array1:

[{Month: 'Jan', Avg: 10}, {Month: 'Feb', Avg: 20}, 
{Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, 
{Month: 'May', Avg: 50}, {Month: 'Jun', Avg: 60}, 
{Month: 'Jul', Avg: 0}, {Month: 'Aug', Avg: 0},
{Month: 'Sep', Avg: 0}, {Month: 'Oct', Avg: 0}, 
{Month: 'Nov', Avg: 0}, {Month: 'Dec', Avg: 0}];

CodePudding user response:

Use Array.map with Array.find

const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const array1 = [{Month: 'Jan', Avg: 10},{Month: 'Feb', Avg: 20},
{Month: 'May', Avg: 50},{Month: 'Jun', Avg: 60}];

const result = months.map(m => array1.find(a => a.Month === m)??{Month: m, Avg: 0});

console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Reference: Array, Nullish

CodePudding user response:

I think this should work pretty much!

var months = [
  "Jan",
  "Feb",
  "Mar",
  "Apr",
  "May",
  "Jun",
  "Jul",
  "Aug",
  "Sep",
  "Oct",
  "Nov",
  "Dec",
];

var array1 = [{
    Month: "Jan",
    Avg: 10
  },
  {
    Month: "Feb",
    Avg: 20
  },
  {
    Month: "May",
    Avg: 50
  },
  {
    Month: "Jun",
    Avg: 60
  },
];

let finalArr = [];

months.filter((e) => {
  let index = array1.findIndex((ele) => ele.Month == e);
  if (index >= 0) {
    finalArr.push(array1[index]);
  } else {
    finalArr.push({
      Month: e,
      Avg: 0
    });
  }
});

console.log(finalArr);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related