What is the method for including the value of a missing object once it has been compared to another array

My task involves dealing with an array of months (var months). I want to filter out the months that are missing in another array of objects (var array1) and add a property Avg with a value of 0 for those missing months.

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}];`

For example, if the array1 has entries for Jan, Feb, May, and Jun, I aim to identify the missing months and assign a value of 0 to the Avg property. This means adding entries like

{Month: 'Mar', Avg: 0}, {Month: 'Apr', Avg: 0}, ...
for the absent months when compared with the months array.

The expected updated version of array1 should look like this:

[{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}];

Answer №1

Optimize your code by using 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);

Check out the following resources for more information: Array, Nullish

Answer №2

This solution seems like it should do the trick!

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Troubleshooting issue: Module fails to reload following JSON.parse error

For QA testing purposes, we have a test page that allows our QA team to replicate server behavior by passing JSON to a mock service. Everything functions correctly when valid JSON is used, but if invalid JSON is provided, an error is returned - which is ex ...

Reloading the ASP.NET MVC bootstrap modal using Ajax for a fresh look

I'm struggling with my bootstrap modal. Whenever I click the submit button, the page refreshes and the modal disappears. How can I keep the modal open after clicking the submit button to display either a success or error message? I am new to MVC and h ...

How can you use a click event or a specific class to indicate voting on a submission with an arrow?

Is it more effective to utilize the approach utilized by reddit for voting, such as using <a onclick="vote('4')">, or should I simply include a class selector like <a class='vote-up' id='4'>? Or is the distinction ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

Unexpected addition of values to a list occurs when scrolling through a web element using Selenium

Having recently delved into Python, as well as programming in general, I am eager to extract data from a webelement that updates dynamically with scrolling using Selenium. A particular post on Stack Overflow titled Trying to use Python and Selenium to scro ...

Adding an object to an array using the Array.push() method deposits an array

Currently, I am extracting the days of absence of my colleague from excel files and storing them in a MongoDB database using Mongoose and Express.js. The process of reading the data is smooth; however, when trying to update the data in the database, an un ...

Utilizing NPM Package Configuration Variables with Docker Commands: A Guide

I have a unique file structure where my package.json contains a single variable called settings which defines the port for the application: package.json ... "settings":{ "port": "3000" }, ... In addition, I've set up a custom script to execute a ...

"Utilizing Jquery to extract data from a form field and combine it with a URL for maximum value

Today, I am delving into the world of jQuery for the first time and finding myself in need of some assistance with a particular problem. While this issue may seem trivial to experienced individuals, it is posing quite a challenge for me. The dilemma lies ...

Content within the Iframe is in the process of loading, followed by

Exploring the code below: <iframe id="myframe" src="..."></iframe> <script> document.getElementById('myframe').onload = function() { alert('myframe is loaded'); }; </script> Is it a possibility that the ifra ...

Retrieving values from nested JSON arrays in PostgreSQL is crucial for accessing all the data within

I am looking to retrieve all the app_index values from the abc array using a raw query. I am working with a PostgreSQL 10.9 database. So far, I have been able to extract up to the abc key successfully by passing the index number of the array. However, my g ...

The AJAX request encountered an error while trying to send a POST request to the http://localhost/upload/undefined endpoint. The

I've been scouring the internet and testing for hours, but I'm still unable to identify the source of the error. I could really use some assistance here. I meticulously followed a tutorial on multiple file uploads with drag & drop functionali ...

Utilizing transitions to control the visibility of div elements

This is what I have achieved so far: function getOffsetRect(elem) { var box = elem.getBoundingClientRect() var body = document.body var docElem = document.documentElement var scrollTop = window.pageYOffset || docElem.scrollTop || body.sc ...

Error: Validation error occurred with document - reason unknown

Recently, I've been working on developing a basic CRUD application using MongoDB as my database. However, I keep encountering an error labeled MongoError: Document failed validation, and I am struggling to pinpoint the issue. The data appears to be s ...

Currently, there is a requirement to include past build outcomes in the HTML test report within the playwright

Is there a way to display the previous build status of each test case for every test case? I have been attempting to use test.info() in playwright, but it seems inaccessible from onTestEnd. One option could be to retrieve the previous build data from Jenki ...

Avoid requesting Chrome Camera permission if it has already been granted during a previous WebRTC call

Our web-conference application utilizes a Flash client for video and audio communication. Video is handled through the Red5 Media Server, while audio is managed using WebRTC. When attempting to access the microphone or camera in Flash, users are required ...

Can the text value be read and its strings changed?

I need to modify the message inside an H2 element with the code provided below. I want to change the text from No results were found for this query: <em class="querytext"> to "No results were found by hello world!, but the catch is that I cannot di ...

Step-by-step guide on removing all elements except the last one using pure JavaScript, without relying on jQuery and utilizing document.querySelectorAll(".someClass"):

Here's my question: Is there a way to remove all elements except the last one with the same class name using vanilla JavaScript without jQuery? In jQuery, I can achieve this in one line like so: $('.someClass').not(':last(2)').re ...

Unable to make changes to a file authored by a different user within Firestore using Vue.js / Firestore

I appreciate any assistance in advance, as this issue has been causing me a lot of frustration! Currently, I am adhering to the firestore data model where users are able to create their own documents associated with their userID. This ensures that users c ...

Ways to initiate the download of an audio link using JS without the need for the browser to redirect to a different page

I am looking to create a script that can automatically download audio files from a website. The problem I'm encountering is that using element.click() to simulate a "click" event doesn't work as expected, as the browser ends up navigating to the ...

Gathering every individual value from the array of ajax objects

controller public function ajaxData(){ $country_id=$this->input->post('country_id',true); $this->load->model('country_m'); $data['states']=$this->country_m->getStates($c ...