Using AngularJS, you can easily merge one array of data into another array

In my coding environment, I am working with two arrays. The first array is called `$scope.workingSchedules` and it contains data related to working hours for different days of the week.

$scope.workingSchedules=[
                       {
                  workingDay:"MONDAY",
                  workingHours:[{fromTime:'1222',toTime:'1300'}]
                      },
                  workingDay:"MONDAY",
                  workingHours:[{fromTime:'1222',toTime:'1300'}]
                     ];

This array can store information for multiple days of the week. Additionally, I have another array named `$scope.workingTime` which has all days of the week listed with empty `workingHours` fields.

$scope.workingTime = [ 
        {   workingDay: 'MONDAY',
            workingHours: []
        },
        {   workingDay: 'TUESDAY',
            workingHours: []
        },
        {   workingDay: 'WEDNESDAY',
            workingHours: []
        },
        {   workingDay: 'THURSDAY',
            workingHours: []
        },
        {   workingDay: 'FRIDAY',
            workingHours: []
        },
        {   workingDay: 'SATURDAY',
            workingHours: []
        },
        {   workingDay: 'SUNDAY',
            workingHours: []
        }
     ];

My goal is to merge the data from the first array (`workingSchedules[]`) into the second array (`workingTime[]`) while keeping any days that are in the second array but not in the first array intact.

To achieve this, I have written the following code:

for(var i=0;i<$scope.workingTime[i].length;i++)
    {
        for (var j=0;j<$scope.workingSchedules[j].length;j++)
        {
          if($scope.workingTime[i].workingDay==$scope.workingSchedules[j].workingDay)
          {
            $scope.workingTime[i]=$scope.workingSchedules[j];

           }

        }
   }

Any assistance or suggestions on how to improve this code would be greatly appreciated. Thank you!

Answer №1

There are a few issues here that need addressing. Firstly, your initial array is incorrect because you are attempting to insert key/value pairs into it. You should either declare it as an object or format all items within it as objects like this: {workingDay:"MONDAY"}, rather than workingDay:"MONDAY",.

Additionally, the way your loops are indexed is peculiar. Consider using i<$scope.workingTime.length instead of

i<$scope.workingTime[i].length
.

Answer №2

When you perform the operation

$scope.workingTime[i]=$scope.workingSchedules[j];
, you are essentially replacing the existing value. It would be more appropriate to use .concat in order to merge the values.

Solution with duplicated entries

var data=[{workingDay:"MONDAY",workingHours:[]},{workingDay:"TUESDAY",workingHours:[]},{workingDay:"WEDNESDAY",workingHours:[]},{workingDay:"THURSDAY",workingHours:[]},{workingDay:"FRIDAY",workingHours:[]},{workingDay:"SATURDAY",workingHours:[]},{workingDay:"SUNDAY",workingHours:[]}]
var workingSchedules=[{workingDay:"MONDAY",workingHours:[{fromTime:"1222",toTime:"1300"}]},{workingDay:"MONDAY",workingHours:[{fromTime:"1222",toTime:"1300"}]}];

data.forEach(function(o) {
  var f = workingSchedules.filter(function(item) {
    return item.workingDay === o.workingDay;
  });
  if (f.length)
    o.workingHours = o.workingHours.concat(f.reduce(function(p, c) {
      return p.workingHours.concat(c.workingHours)
    }));
});

console.log(data)

Solution with distinct values

var data=[{workingDay:"MONDAY",workingHours:[]},{workingDay:"TUESDAY",workingHours:[]},{workingDay:"WEDNESDAY",workingHours:[]},{workingDay:"THURSDAY",workingHours:[]},{workingDay:"FRIDAY",workingHours:[]},{workingDay:"SATURDAY",workingHours:[]},{workingDay:"SUNDAY",workingHours:[]}];
var workingSchedules=[{workingDay:"MONDAY",workingHours:[{fromTime:"1222",toTime:"1300"}]},{workingDay:"MONDAY",workingHours:[{fromTime:"1222",toTime:"1300"}]},{workingDay:"MONDAY",workingHours:[{fromTime:"1400",toTime:"1700"}]}];

data.forEach(function(o) {
  var f = workingSchedules.filter(function(item) {
    return item.workingDay === o.workingDay;
  });
  if (f.length) {
    o.workingHours = o.workingHours.concat(f.reduce(function(p, c) {
      var exists = p.some(function(item) {
        return item.fromTime === c.workingHours[0].fromTime && item.toTime === c.workingHours[0].toTime;
      });
      return exists ? p : p.concat(c.workingHours);
    }, []));
  }
});

console.log(data)

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

I created a custom discord.js-commando command to announce all the channels that my bot is currently active in, however, encountered an unexpected error

const Commando = require('discord.js-commando'); module.exports = class AnnounceCommand extends Commando.Command { constructor(client) { super(client, { name: 'announce', aliases: ['an'], ...

Concatenating columns values from an array to lists of nested lists

I am looking to combine 3 arrays of 3x1 into a list of lists where each list represents a single row 1x3 from each array. For example, I want to transform this: [array([['0.6913'], ['0.7279'], ['0.724']], dtype= ...

Timer repeatedly triggered until nausea ensued (native v8natives.js:1582)

My website is running extremely slow and after conducting a test using the Timeline feature in Chrome Tools for Developers, I discovered that there is a Timer firing in a JS file called v8natives.js for about 9 seconds. After checking my Wordpress plugins, ...

"Implementing x2js in your project on-the-fly with the help

Hey there, does anyone have the link for x2js that they could share with me? I'm interested in loading this JavaScript file dynamically. I tried using the code below but it didn't work: EffectaJQ.ajax({ async: false, url: "https ...

MongoDB failing to enforce unique constraints on partial indexes

I have a set of data that looks like this: { name: "Acme co." add4: "", nationalNumber: "+13412768376" }, { name: "Acme Inc.", add4: "6345", nationalNumber: "" } My goal is to insert these records into a collection, but only if they are uni ...

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

Asynchronous task during stream processing

Can anyone assist me? I am looking to read a file as a stream and when processing the initial chunk, I need to create a database table in an async manner. To achieve this, I want to develop a duplex/transformer stream that would be responsible for creatin ...

The default value of the input color in HTML/NextJS does not update when changed

Issue: The color input does not change when the default value (#ffffff) is declared. https://i.sstatic.net/BpqUj.png However, it works normally if I don't declare a default value. https://i.sstatic.net/0dBd6.png Note: Using NextJS framework. <i ...

The Next.js error message reads: 'Issue with setting properties on undefined entity (specifically 'hook')'

This issue seems to occur either when the app is launched or when updating the Redux state. It may not show up consistently for every state update, but for some reason it persists throughout the entire app. What I have attempted so far: Removing node mod ...

A comprehensive guide on retrieving data from API across several pages

Struggling with pulling data from an API using React and facing the challenge of retrieving more than one page of data. "info": { "count": 493, "pages": 25, "next": "https://rickandmortyapi.com/api/character/?pa ...

Locate the closing anchor tag following the image

I need to locate the closing anchor tag that wraps an image with the class name "cat-image" in order to move a div right after it. However, I am unable to modify the HTML by adding IDs or classes to the anchor or image tags. Below is an example of the HTM ...

How can one selectively apply a class to the initial DIV within a collection of dynamically generated DIV elements without relying on jQuery?

I am currently working on implementing a slideshow within a modal using AngularJS and Bootstrap. My challenge lies in dynamically creating DIVs, but specifically adding the active class to only the first DIV. Is there a way to achieve this without relying ...

Having trouble getting Ajax post to function properly when using Contenteditable

After successfully implementing a <textarea> that can post content to the database without needing a button or page refresh, I decided to switch to an editable <div> for design reasons. I added the attribute contenteditable="true", but encounte ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

How can you stop a document event listener from triggering?

Utilizing document.addEventListener('touchstart', this.onDocument); allows me to recognize when a user taps outside of an element. However, within my button click handler, the following code is present: toggleItemActive(e) { e.stopPropa ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Is there a way to create a JavaScript-driven search filter that updates automatically?

My website showcases a lineup of League of Legends champion icons, with one example shown below: <div class = "champion"> <p>Aatrox <img class = "face_left" src = "images/small/Aatrox.png"> <div class = "name" onmouseover="if(cha ...

Sending an event to a component that has been rendered in Vue

I'm currently in the process of developing a custom rendered component that will execute a function when clicked on: // Creating a standard Vue component with a render function Vue.component('greeting', { methods: { sayHello(){ ...

The React engine is triggering an error stating "Module not found."

Utilizing react-engine to enable the server with react component access. Through react-engine, you can provide an express react by directing a URL and utilizing res.render. The documentation specifies that you need to supply a path through req.url. app.use ...

Displaying JSON data dynamically by iterating through it in a loop

While working with JSON data in a loop, I noticed that the code quality does not meet my expectations. I have a feeling that I might be missing something in my approach. $(function(){ $.getJSON('data.json', function(data){ let content ...