Analyzing two sets of data and populating any absent information

My goal is to compare the dates from 2 separate arrays and extract the names that match, pushing them into a new array. For any missing dates, I want to push '0' instead.

This is my current approach:

var data = [{
  name: 'Amy',
  date: '2020-01-01'
}, {
  name: 'John',
  date: '2020-01-02'
}, {
  name: 'Sara',
  date: '2020-01-04'
}];

var fulldate = ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05'];
var newData = [];
var len = data.length;
for (var i = 0; i < len; i++) {
  if (data[i].date == fulldate[i]) {
    newData.push(data[i].name);
  } else if (data[i].date != fulldate[i]) {
    newData.push("0")
  }
}

console.log(newData);

The issue arises when encountering an unmatched date as it halts the process:

Amy,John,0

This is what I am aiming for:

Amy, John, 0, Sara, 0

Answer №1

Given that the arrays are already sorted by date, we can utilize a variable called dataIdx to iterate through the data array using Array.map() to simplify the for loop process.

var data = [{name:'Tom', date:'2020-01-01'}, {name:'Lisa', date:'2020-01-03'}, {name:'Mike', date:'2020-01-05'}];

var fulldate = ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05'];

var dataIdx = 0;
var newData = fulldate.map(date => data[dataIdx] && data[dataIdx].date == date ? data[dataIdx++].name : '0');
console.log(newData);

Answer №2

To achieve the most concise solution, it is best to utilize a combination of the map and find functions. Below is a one-liner that showcases this:

const data = [{
  name: 'Alice',
  date: '2020-01-01'
}, {
  name: 'Bob',
  date: '2020-01-02'
}, {
  name: 'Eve',
  date: '2020-01-04'
}];

const fulldate = ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05'];

const result = fulldate.map(x => (data.find(y => y.date === x) || {name: 0}).name)

console.log(result)

Answer №3

To optimize your code, it is recommended to utilize the map and filter functions in JavaScript. By applying the map function to the fulldate array, the obj variable can identify objects with matching dates to the current value of el. A ternary operator is then used in the return statement to output the name if an object is found, or 0 if not.

var data = [{
  name: 'Amy',
  date: '2020-01-01'
}, {
  name: 'John',
  date: '2020-01-02'
}, {
  name: 'Sara',
  date: '2020-01-04'
}];

var fulldate = ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05'];


var result = fulldate.map((el) => {
  let obj = data.filter(item => (item.date == el))  
  return (obj[0]) ? obj[0].name : 0;
})

console.log(result);

Answer №4

  • Within the code snippet provided, a for-loop is utilized based on the length of the 'data' variable, resulting in a loop that matches the length of the 'fulldate' variable instead of just the 'data' variable. To correctly compare dates, it is necessary to incorporate an additional loop within the existing one to find the index of the matching date.
  • To streamline this process, you can replace the for loop with the Array.prototype.map function. By utilizing Array.prototype.findIndex within the map function, you can accurately locate the index of the matched date.

Here's an example:

var data = [{
  name: 'Amy',
  date: '2020-01-01'
}, {
  name: 'John',
  date: '2020-01-02'
}, {
  name: 'Sara',
  date: '2020-01-04'
}];

var fulldate = ['2020-01-01', '2020-01-02', '2020-01-03', '2020-01-04', '2020-01-05'];

const result = fulldate.map((date) => {
  const existed = data.findIndex(item => item.date === date);
  return existed >= 0 ? data[existed].name : 0
});
console.log(result);

Answer №5

var userNames = [{
  name: 'Emily',
  date: '2020-01-01'
}, {
  name: 'Mike',
  date: '2020-01-02'
}, {
  name: 'Lisa',
  date: '2020-01-04'
}];
var allDates = [
  '2020-01-01',
  '2020-01-02',
  '2020-01-03',
  '2020-01-04',
  '2020-01-05'
];
var updatedData = [];
for(var j = 0; j < allDates.length; j++) {
  var isFound = false;
  for(var m in userNames) {
    if(userNames[m].date == allDates[j]) {
      updatedData.push(userNames[m].name);
      isFound = true;
      break;
    }
  }
  if(!isFound)
    updatedData.push("0");
}
console.log(updatedData);

Answer №6

It's recommended to use 'let' or 'const' for variable declaration instead of var. Learn more about the differences here: var vs let vs const

If you're searching for a specific result, you can achieve it using the map and find JavaScript functions.

const fulldate = ["2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04", "2020-01-05"];
const data = [
 {name: "Amy", date: "2020-01-01"},
 {name: "John", date: "2020-01-02"},
 {name: "Sara", date: "2020-01-04"}
];

const result = fulldate.map(date => {
    const matchingDate = data.find(nameDateObj => nameDateObj['date'] === date);
    return matchingDate ? matchingDate['name'] : 0;
});

console.log(result)

Also, keep in mind that this task can also be accomplished using findIndex instead of find.

fulldate.map(date => {
     const matchingDateIndex = data.findIndex(nameDateObj => nameDateObj['date'] === date);
     return matchingDateIndex > -1 ? data[matchingDateIndex]['name'] : 0; 
});

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

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

The webpage fails to display Vue Bootstrap radio buttons in a filled state

Hey there! I've been working on a project using vuejs and bootstrap-vue-3. My goal is to allow users to print data about the company, so I created a print scss file for that purpose and added some styles. However, I'm facing an issue where the ra ...

`The Streaming module within React Native`

I am facing an issue in my React Native project where I want to use a node library that depends on stream (require('stream')). The problem arises with the error stream could not be found within the project because stream is a nodejs package not ...

Tips for properly formatting the bound value prior to its display while utilizing ng-model

Currently, my code looks like this: $scope.value = 0; /// <input type="number" ng-model="value" placeholder="This is not displaying" /> As you can see, the default value of 0 shows up inside the number input instead of the desired placeholder. I ...

What causes the unexpected behavior when utilizing PHP's array_reverse() function on an array of arrays?

Recently, I encountered an issue with the array_reverse() function in PHP. Typically, this function is used to reverse the elements of an array, but surprisingly, it didn't work as expected when dealing with an array of arrays. This unexpected behavio ...

Creating a dynamic system in C# to simultaneously launch multiple forms using an array of Form objects

I'm attempting to open multiple forms of the same type once a file is opened. In the code below, I expect to see 10 instances of the 'Test' form appear when the program is executed. While I can see multiple forms being created in the RAM, th ...

Is there any method to determine whether a floated element has been pushed down?

Imagine a dynamic menu with floating elements, each set at a width of 150px. As the menu's width decreases, the elements progressively move to the next row. You are contemplating how to detect when an element has been moved down. One approach could b ...

Issues with navigating jQuery UI links while offline in Google abound

Hello, I am a newcomer to jQuery and I am facing an issue with my code. I added the <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> but for some reason, my jQuery is not working. I have tried searching ...

Modify the -webkit-text-stroke- hue using JavaScript

I've been working on a website that features text with "text stroke", and I am attempting to dynamically change the color of this text stroke using JavaScript. My goal is to have four different color options available. However, as it is based on webk ...

Tips for passing dynamic latitude and longitude values to a JavaScript function within an AngularJS framework

I am facing an issue with displaying a dynamic marker on Google Maps. I can show a static lat long marker, but I am struggling to pass dynamic lat long values to the function. How can I pass {{names.lat}}, {{names.longitude}} to the function so that I can ...

An array of Promise<Employee> cannot be used as a parameter for an array of type Employee[]

I am currently facing an issue with loading my Collection of Employees from a Firestore Database and fetching a 'Workday' for each Employee, which is stored as a Document in a Subcollection named 'Employees'. Below is the code snippet I ...

Exploring the process of querying and modifying subdocuments in MongoDB

As I work on updating a subdocument in MongoDB with Express, I have a specific route set up to find the exact object for updating. Currently, I am only able to replace the entire document with a new one. Is it acceptable to keep it like this or is there a ...

Manipulating element height in AngularJS

My goal is to utilize the bootstrap style for a fixed navigation bar at the top of the page. By using navbar-fixed-top, I can fix an element to the top. The visibility of #subnav will be determined by the value of showsubnav. <div id="backnav"> ...

What sets structs apart from other data types?

In the C programming language, it is not possible to directly return an array from a function. Instead, we typically return a pointer to an array. However, there is something interesting about structs that allows them to be returned by functions even if th ...

A guide to defining a color variable in React JS

I am trying to use a random color generated from an array to style various elements in my design. Specifically, I want to apply this color to certain elements but am unsure how to do so. For example, I know how to make a heading red like this: const elem ...

What is the reason that this jQuery code is exclusive to Firefox?

I am currently working on a code snippet that enables users to navigate back and forth between images by displaying them in a lightbox at full size. The code functions flawlessly in Firefox, however, it does not seem to have any effect on IE, Chrome, and S ...

Vanilla.js with Vue does not support the onclick event functionality

Currently, I am facing the need to utilize vanilla.js in my application due to the presence of html entities retrieved from the database that require special treatment. Since the babel compilation process has already concluded, I am resorting to manipula ...

When accessing a page from a link, JavaScript sometimes does not immediately execute on the first attempt

I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I' ...

Ways to verify the presence of a Hash value within an array?

Below is the code snippet for my setup: project_JSON = JSON.parse teamList = Array.new project = Hash.new() project["Assignee Name"] = issue["fields"]["assignee"]["displayName"] project["Amount of Issues"] = 0 if !teamList.include?(issue["fields"]["ass ...

What causes a functional component's nested function to access an outdated state value?

My component implements infinite scrolling to fetch and display posts using an IntersectionObserver. The API call made by the component depends on the current number of fetched posts, which is passed as an offset to the API call. The objective is to displ ...