Merge two arrays based on date and sort them using Angular.js/JavaScript

I am facing a challenge where I have two JSON arrays, each containing a field named date. My goal is to compare the two arrays and merge them into a single array. Check out the code snippet below:

var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08'}];

var secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09'}];

In this scenario, I need to analyze both arrays based on their dates and combine their values into one unified array. The desired output should look like this:

var finalArr=[{'name':'Ram','date':'2017-12-06','model':'mmm'},{'name':'Raja','date':'2017-12-07','model':''},{'name':'Rahul','date':'2017-12-08','model':''},{'name':'','date':'2017-12-09','model':'rrr'}]

The expected outcome has been provided above. Currently, my attempt to achieve this looks like as follows.

angular.forEach(firstArr,function(obj1){
            angular.forEach(secondArr.task,function(obj2){
                if (new Date(obj1.date)=== new Date(obj2.date)) {

                }
            })
        })

However, I am encountering some confusion regarding the different lengths of the two arrays, as they may or may not be equal.

Answer №1

My main focus is on the JavaScript part rather than the specific Angular version.

Approach

  • To merge objects based on a date string, you can create a hashMap where the date string acts as the property and the object as its corresponding value.
  • You can then utilize Object.assign for merging the objects. If that's not feasible, resorting to a for..in loop or employing two separate loops to manually set properties might be necessary.
  • Finally, iterate over this hashMap to gather the grouped objects.

Example:

var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08'}];

var secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09'}];

var hashMap = {};
[firstArr, secondArr].forEach(function(arr) {
  arr.forEach(function(obj) {
    hashMap[obj.date] = Object.assign(Object.create(null), hashMap[obj.date] || {}, obj);
  })
});

var result = Object.keys(hashMap).map(x=> hashMap[x]);
console.log(result)

Answer №2

To combine objects with the same date, you can utilize the array#reduce method. Within the array#reduce function, merge objects that share the same date and extract all values using Object.values().

var firstArray=[{'name':'Alice','date':'2018-02-15'},{'name':'Bob','date':'2018-02-16'},{'name':'Charlie','date':'2018-02-17'}],
    secondArray=[{'color':'red','date':'2018-02-15'},{'color':'blue','date':'2018-02-18'}];

var mergedResult = firstArray.concat(secondArray).reduce((accumulator, obj) => {
  accumulator[obj.date] = Object.assign({}, accumulator[obj.date] || {name:'', color: ''}, obj);
  return accumulator;
},{});

var finalOutput = Object.values(mergedResult);
console.log(finalOutput);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Give this a shot:

let finalArray = [];
angular.forEach(firstArray, function(value) {
    angular.forEach(secondArray, function(element) {
        if (value.date === element.date) {
            finalArray.push({ name: value.name, date: value.date, model: element.model });
        }
    });
});

Answer №4

Give this a try. If you wish to keep the original arrays intact, you'll need to create deep clones of them beforehand. Unlike Edison's approach, this method will also incorporate items from the second array.

var firstArr=[{'name':'Ram','date':'2017-12-06'},{'name':'Raja','date':'2017-12-07'},{'name':'Rahul','date':'2017-12-08' }];

var secondArr=[{'model':'mmm','date':'2017-12-06'},{'model':'rrr','date':'2017-12-09' }];

const newArr = (arr1, arr2) => {
  const finalArr = arr1.map((firstElement) => {
    firstElement.model = "";
    arr2.forEach((secondElement, index) => {
      if (secondElement.date === firstElement.date) {
        firstElement.model = secondElement.model;
        arr2.splice(index, 1);
       }
    });
    return firstElement;
  });
  arr2.forEach((element) => {
    element.name = "";
    finalArr.push(element);
  });
  return finalArr;
};

console.log(newArr(firstArr, secondArr));

Answer №5

Angular is a robust framework with a vast library, but it only requires the correct syntax in the view to get started.

This example worked flawlessly without any coding in the controller:

var app = angular.module("app", []);

app.controller("ctrlA", function($scope) {
  var firstArr = [{
    'name': 'Ram',
    'date': '2017-12-06'
  }, {
    'name': 'Raja',
    'date': '2017-12-07'
  }, {
    'name': 'Rahul',
    'date': '2017-12-08'
  }];

  var secondArr = [{
    'model': 'mmm',
    'date': '2017-12-06'
  }, {
    'model': 'rrr',
    'date': '2017-12-09'
  }];

  $scope.ul = firstArr.concat(secondArr);

})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrlA">
  <ul>
    <li ng-repeat="li in ul | orderBy:'date'">
      {{li.name ? li.name : li.model}} - {{li.date}}
    </li>
  </ul>
</div>

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

Displaying a loading spinner image as PHP script runs

Hey there! I've been experimenting with using a script to show a loading bar while my PHP code is running. I followed the instructions on this website, but even after following the exact steps, my loading bar still isn't showing up. Any suggestio ...

Issue with the transmission of FormData and string data to PHP

Struggling to properly handle sending file data and string data together through ajax to PHP. Having trouble retrieving the correct string data from $_POST[] in PHP, resulting in only receiving the initial alphabet of a string instead of the specific produ ...

Guide to setting up parameterized routes in GatsbyJS

I am looking to implement a route in my Gatsby-generated website that uses a slug as a parameter. Specifically, I have a collection of projects located at the route /projects/<slug>. Typically, when using React Router, I would define a route like t ...

Transferring JSON data using DWR (Direct Web Remoting)

Utilizing DWR for AJAX calls in my project involves the conversion of JavaScript objects to Java objects by analyzing the Java class. My goal is to send and receive a JSON-like structure through DWR. For example: JavaScript Object: { "name" : "TamilVe ...

Securing paths in NuxtJS

Hey there! I'm just getting started with nuxt and have set up the following routes: /home /dashboard /login My goal is to secure the /dashboard route only for users who are logged in and have a token stored in LocalStorage. The simplest solution ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Condensed conditional statement in PHP Arrays

Attempting to use shorthand if in a PHP array has not been successful, even when true is enclosed in braces. The functioning code: echo Nav::widget([ 'options' => ['class' => 'navbar-nav navbar-right'], 'i ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Retrieve an array of items from the Firebase snapshot

Currently in the process of retrieving items from my Firebase database, I am utilizing a snapshot that is generated when the page loads. I have collected the values of each object in an array and I am now attempting to add an item from each object into a s ...

Sending input values from textboxes to the Controller

I currently have the following code snippets: Home Controller: public IActionResult Index() { return View(); } public ActionResult Transfer() { string path = @Url.Content(webRootPath + "\\SampleData\\TruckDtrSource.json&q ...

A Fresh Approach for Generating Unique UUIDs without Bitwise Operators

To generate UUIDs in TypeScript, I have implemented a method inspired by the solution provided on Stack Overflow. The code effectively converts JavaScript to TypeScript. generateUUID(): string { let date = new Date().getTime(); if (window.performa ...

Sorting an array of elements in JavaScript based on their value relationships

I need help grouping the elements of an array based on their inner array groupings Input: const arr = [ [123, 243], [123, 435], [736, 987], [987, 774], [123, 666], [774, 999], [098, 980], ]; Output: Result = [[123, 243, 435, 666],[736, ...

Enhancing numbers by incorporating different digits

I am working on a program where I need to create an array from 1 to 100. Within this array, I want to store each number along with the sum of its individual digits. For example, if the number is 6, the stored value should be 6 because 6 + 6 equals 12. Si ...

"Unraveling the Mystery of jQuery In

I am facing an issue with integrating jQuery into my code. I have always followed the same method, which has worked in the past, but now it seems to be causing problems for me. I suspect it may be because I am not on my usual laptop, although when I visite ...

Struggling with retrieving data from a file in Angular service while using node-webkit. Unable to make it functional

I've been struggling for a while and gone through numerous solutions, but I can't seem to figure out why this code isn't functioning: I have a requirement to pass data between controllers, so I created a service, right? (The data is coming ...

ExpressJs does not support query parameters with the router.get method

I am currently working on developing an Express app. Here is the code snippet I am using: const express = require("express"); const router = express.Router(); router.get("/:id", ControllerHandler(UserController.getSingle, GetUserReque ...

Dividing a JSON string and incorporating them into individual tds using AngularJS

Currently, I am working on extracting values from a JSON string by splitting it at the ":" and displaying the two values in separate td tags. function testCtrl($scope) { $scope.response = {"name":["The name field is required."],"param":["Hobby: Coding", " ...

What is the method to disable response validation for image endpoints in Swagger API?

I'm working with a Swagger YAML function that looks like this: /acitem/image: x-swagger-router-controller: image_send get: description: Returns 'image' to the caller operationId: imageSend parameters: ...

Initiate an Ajax request from a hyperlink

Is it possible to trigger an Ajax request from a hyperlink? I am interested in updating the inner html of a div element upon clicking on a hyperlink through JavaScript. ...