JavaScript array manipulation

I am working with an array of objects that have a year and count property like this:

[{year: "1920", count: 0}, {year: "1921", count: 2}, {year: "1925", count: 0}, {year: "1930", count: 21}, ....]

My goal is to populate all the years between a starting year (e.g. 1900) and an ending year (e.g. 2000) in the array with objects like {year: -year-, count: 0}. For example, filling in the years between 1900 and 1920, 1921 and 1925, 1925 and 1930, and 1930 and 2000.

If anyone has encountered a similar issue and can offer some guidance, I would greatly appreciate it!

Edit: So far, I have attempted a simple for loop, checking each iteration if the year is in the array. However, I believe there may be a more efficient and effective solution to this problem.

Answer №1

To start, you can initialize an object using the current years array and then create a new array by checking if the year is present in that object:

const presentYear = [{year: "1920", count: 0}, {year: "1921", count: 2}, {year: "1925", count: 0}, {year: "1930", count: 21}];

const presentYearObj = Object.fromEntries(presentYear.map(k=>[k.year, k]));

const allData = Array.from({length:101}, (_,i)=>presentYearObj[`${1900+i}`] || ({year:`${1900+i}`, count:0}));

console.log(allData);

Answer №2


let years =
    [
        {year: "1920", count: 0},
        {year: "1921", count: 2},
        {year: "1925", count: 0},
        {year: "1930", count: 21}
    ]

let yearNumbers = years.map(item => {
    return +item.year
})

console.log(yearNumbers)

for (let j = 1900; j < 2000; j++) {
    if (!yearNumbers.includes(j)) {
        years.push({year: j + '', count: 0})
    }
}

console.log(years.length)

Answer №3

function generateYearCounts(startYear, endYear, existingData) {
  
  let existingCounts = {};
  existingData.map(item => existingCounts[item.year] = item.count);
  
  let yearsData = [];
  for (let year = startYear; year <= endYear; year++) {
    yearsData.push({ 
      year: year.toString(), 
      count: existingCounts[year] || 0
    });
  }
  
  return yearsData;
  
}

let existingYearsData = [
        { year: "1920", count: 0},
        { year: "1921", count: 5},
        { year: "1925", count: 0},
        { year: "1930", count: 10}
  ];

existingYearsData = generateYearCounts(1900, 2000, existingYearsData);
console.log( existingYearsData );

This function constructs a new array by filling in the count values based on the existing data array.

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

the least amount of steps required to organize a list

Currently, I am working on a problem from Codeforces that involves sorting an array by either moving the elements to the beginning or the end of the array. Initially, I thought it was related to finding the longest increasing subsequence, but that approa ...

Vue.js Pagination Issue - Current Page Number Beyond Maximum Page Limit

I'm currently working on incorporating pagination into a table showcasing data for Magic: The Gathering cards. By default, the table displays only 5 items per page, with options to select pages and set the number of results per page at the bottom of ...

Contrast two arrays using Ruby and generate a new array consisting of elements from both arrays

I have a dilemma involving two arrays, array1 and array2. My goal is to compare these arrays and generate a third array, array3, that includes elements from array2 which are not present in array1. Here's what I've attempted so far: my_buckets = ...

What is the method for selectively applying a "fade to black" mask to an input field?

For my current project, I need to incorporate a design feature where a "fade to black" mask gradually appears on the left side of an input field once the text content reaches the maximum visible width of the input box. The image below provides a visual re ...

What is the best way to pass card data between Vue.js components?

My application consists of two components: DisplayNotes.vue, which displays data in card format retrieved from the backend, and UpdateNotes.vue, which allows users to update existing data by opening a popup. The issue I'm facing is that when a user cl ...

Does AngularJS have a feature similar to jQuery.active?

As I utilize selenium to conduct tests on my application, I am encountering numerous ajax calls that utilize $resource or $http. It would be convenient if there was a method in angular to monitor active ajax requests so that selenium could wait until they ...

What is the reason behind JavaScript libraries opting for a structure of [{ }] when using JSON?

I have been experimenting with various Javascript libraries, and I've noticed that many of them require input in the format: [{"foo": "bar", "12": "true"}] As stated on json.org: Therefore, we are sending an object within an array. With this observ ...

AgGrid's magical dropdown feature

Struggling to integrate a bootstrap-4 dropdown menu with AgGrid, I'm facing an issue where the data table overlaps the dropdown when the html is present. Attempts to increase the z-index have not yielded results. Below is the html code snippet: < ...

What is the best way to handle errors generated by my jsdom.jqueryify callback function?

When running this code in node.js, the output is a stack trace of an error that occurs on line 9. Surprisingly, the error on line 7 seems to be 'absorbed' by Node. Even when wrapped in a try/catch statement, the detailed stack trace output is not ...

"Exploring the World of Arduino with Structs

As a novice in Arduino programming, I am currently exploring the usage of structs. I am facing a challenge in declaring an array inside the struct and utilizing it effectively. Specifically, I am uncertain about how to declare and utilize arrays such as ...

What is the best method for choosing all options in a select box in IE without experiencing the scrolling effect?

Here's the scenario: I have a select element with multiple options and a checkbox that allows users to select/deselect all options. The issue arises in Internet Explorer, where selecting all options using code causes the entire select box to scroll un ...

Creating an array of a specific field within a JSON string using the collect() method of objx is a straightforward process

Here is the JSON string I am working with: var data = [{"first":"3","second":"1"},{"first":"5","second":"5"},{"first":"7","second":"1"}]; Currently, I am using the following code - objx(data).collect("first") I am expecting to receive an array like [3 ...

Display Information in Tooltip Using Text from a Different Source

I'm seeking a way to create tooltips on a webpage that provide definitions for specific words. However, these definitions are located on a separate page within the same website. Is it possible for me to extract the text I need to display in the toolti ...

Bot is being inundated with messages containing no content

My discord.js version is 14.0.3. I'm facing an issue where the message content is not being retrieved correctly. To solve this, I set up a client.on('messageCreate') event handler: client.on('messageCreate', async (message) => ...

Selenium with JavaScript: The Battle of Anonymous Functions and Named Functions

When working with Selenium JavaScript, the prevalent advice I come across online suggests that the most effective approach to handle the asynchronous behavior of JavaScript is by utilizing anonymous functions with .then() for locating/interacting with elem ...

What exactly does the term "new.target" refer to?

The ECMAScript 2015 specification references the term new.target a total of three times - once in section 14.2.3: Although Contains typically does not analyze most function forms, it is specifically used to identify new.target, this, and super usage wit ...

Determine the number of grid cells that include coordinates of x and y points

Here is the code I've written: import numpy as np import matplotlib.pyplot as plt x = np.random.randint(-960,960,15) y = np.random.randint(-540,540,15) fig, ax = plt.subplots(figsize=(20, 11)) ax.scatter(x, y, marker='o', color='red&ap ...

Launch a YouTube video within a sleek and stylish Bootstrap modal popup

I am currently extracting video data from my SQL table. The fields in the table are as follows: - sidebar_video_id (auto increment) - sidebar_video_nev - sidebar_video_link (full URL) - sidebar_video_v_id (video ID at the end of the URL) What I'm tr ...

Error encountered when pushing Angular data to Django for user login form: 'Unexpected token < in JSON at position 2' while attempting to parse the JSON

I believe the < symbol is appearing because the response is in HTML or XML format. This is the section of my code where the login process is failing. public login(user) { this.http.post('/api-token-auth/', JSON.stringify(user), this.ht ...

"Combining Array Elements in jQuery: A Guide to Merging Two Array Objects

enter : var b= [{ "cat_id": "1", "cat_name": "teaching" }]; var a= [ { "username": "r", "password": "r" }]; I desire the following result: [{"username":"r","password":"r","cat_id":"1","cat_name":"teaching"}] ...