Assign characteristics to particular items within an array

When working with AngularJS/Javascript, I have an array of objects that each contain a date. My goal is to order these objects by date and then add an attribute to the last object that has a specific datetime. If there are two objects with the same date, the attribute should be added to the one with the latest time. If there is only one object with a particular date, then the attribute should be added to that object.

For example:

input:   var arr = [
          {A: {"Date": "2017-08-14T15:15:00"} B:{}}
          {A: {"Date": "2017-08-14T16:15:00"} B:{}} //<--- Add attribute to this object 
         ] 

output:  var arr = [
          {A: {"Date": "2017-08-14T15:15:00"} B:{}}
          {A: {"Date": "2017-08-14T16:15:00"} B:{} C:{"NewAttribute": "true"}}
         ] 

I am unsure how to approach programming this. Initially, I thought about using a for loop to compare all the objects, but I'm stuck on how to implement it.

Answer №1

It seems like I have understood your requirement:

var data = [
  {A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // will not receive the new property
  {A: {"Date": "2017-08-14T16:12:00"}, B:{}}, // will receive the new property
  {A: {"Date": "2017-08-14T15:15:00"}, B:{}}, // will receive the new property
  {A: {"Date": "2017-08-14T16:14:00"}, B:{}}, // won't get the new property
  {A: {"Date": "2017-08-14T16:14:00"}, B:{}}  // will receive the new property
];

// sort the array by date in descending order
var sortedData = data.sort(({A: { Date: d1 }}, {A: { Date: d2 }}) => new Date(d2).getTime() - new Date(d1).getTime());

// add the new property as required
sortedData.reduce((acc, obj) => {
  var dateValue = obj.A.Date;
  if (acc !== dateValue) {
    obj.C = {"NewAttribute": "true"};
  }
  return dateValue;
}, '');

// reverse the array
var finalResult = sortedData.slice().reverse();

console.log(finalResult);

Answer №2

To start, it is recommended to arrange the array based on the date by utilizing Array.prototype.sort(). After sorting, you can proceed to add a new attribute to the final element:

let array = [
      {A: {"Date": "2017-08-14T15:15:00"},B: {}},
      {A: {"Date": "2017-08-16T16:15:00"},B: {}},
      {A: {"Date": "2017-08-24T16:15:00"},B: {}},
      {A: {"Date": "2017-08-24T16:15:00"},B: {}, C: {}}
    ],
    alphaArray = 'abcdefghijklmnopqrstuvwxyz'
      .toUpperCase()
      .split(''),
    lastItemLength = 0;

// Sorting the array
array.sort(function (x, y) {
  return new Date(y.A.date) - new Date(x.A.date);
});

// Determining the length of properties in the last element
lastItemLength = Object.keys(array[array.length - 1]).length;

// Adding a new attribute to the last element with an appropriate name
array[array.length - 1][alphaArray[lastItemLength]] = {
  "NewAttribute": "true"
};

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 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

What is the best way to import a TypeScript file in index.js?

I've recently developed an application using the react-express-starter template. I have a "server" directory where the backend is created by nodejs, containing an index.js file: const express = require('express'); const app = express(); c ...

Having difficulty converting a list of intricate objects into a CSV format

I am faced with a challenge of handling an array of complex objects, some of which may contain arrays of more objects. My goal is to convert this data into a CSV file. However, whenever there is a list of objects, the information appears as [object Object] ...

Attempting to replicate the action of pressing a button using Greasemonkey

I am currently working on a greasemonkey script to automate inventory updates for a group of items directly in the browser. I have successfully implemented autofill for the necessary forms, but I am facing challenges with simulating a click on the submissi ...

Is there a way to adjust text animations so they appear separately in their designated space?

During my project, I decided to incorporate some CSS animations onto the site. However, I encountered a problem with the overflow: hidden attribute not functioning as anticipated. Here is the code snippet I used: .jumbotron { height: 100%; heigh ...

What is the method for obtaining the 2D coordinates (x, y) from a sorted 1D list ranging from 0 to n, considering the width and height provided?

Given a 1d list storing the indexes of an image as 0,1,2,3,4,5 ....(w*h) instead of (0,0), (0,1),(0,2)...(w,h) (where w and h are the width and height of the image), how can we determine the corresponding indexes (x,y) for a specific index like 57? It sho ...

Facing a problem with model binding in Angular's scope?

Greetings! I am a beginner in AngularJS and currently working on developing a chat application for the Android platform using Socket.IO, AngularJS, and Ionic. However, I have encountered an issue with my chat page. I am attempting to connect the textbox to ...

Have I got it all wrong with the way Controllers communicate with Services and how I conduct unit testing?

Currently, I am in the process of developing an AngularJS application and I want to ensure it follows best practices. When making external API calls using either $resource or $http, I always do this within a separate Service or Factory. However, I am unsur ...

Unable to retrieve the ZIP archive generated dynamically

I am facing an issue while attempting to generate a dynamic output from MySQL queries and create an archive. Below is the code snippet I have been working with: var async = require("async"); var mysql = require("mysql"); var express = require("express"); ...

Encountering an Internal Server error with Mongoose in Node.js

My latest project is a web application designed for photo sharing. One particular route in the app is responsible for retrieving and displaying photos from all users in the following array. This is the route: router.get('/getphotos',function(r ...

Support for both Fetch API and XMLHttpRequest across browsers is imperative for seamless data retrieval and

Currently, I am diving into the world of ajax programming techniques. However, I recently discovered that the XMLHttpRequest is deprecated and now I must transition to using the Fetch API. The catch is, according to MDN, the Fetch API is still considered e ...

What is the best way to iterate over a multidimensional array in Angular/Ionic?

I've been struggling to find a solution tailored for looping in a .ts file instead of HTML. My main objective is to iterate over an array and compare the entered value with the keys. If there's a match, I want to retrieve the values stored withi ...

How can a function in one React component be invoked from another component?

Currently in my React project's App.js, I am calling the this.searchVenues() function in my return statement. It works, but the implementation is messy and I know there must be a more efficient way to achieve this. The searchVenues() function is locat ...

Dynamically import React Material UI Icons when needed

The concept here revolves around importing react material UI icons only when necessary, especially in situations where we may not know the icon name during compile time. (Ensuring that we have valid icon names) My method involved using a require statement ...

Implementing an API route to access a file located within the app directory in Next.js

Struggling with Nextjs has been a challenge for me. Even the most basic tasks seem to elude me. One specific issue I encountered is with an API call that should return 'Logged in' if 'Me' is entered, and display a message from mydata.tx ...

What is the best method for retrieving a local value in Javascript?

Consider a scenario where there exists a variable named animationComplete (which is part of a 3rd-party library) and a function called happenAfterAnimation: An easy solution would involve the following code snippet: while(!animationComplete) { // Do n ...

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Creating Seamless, Unified Shape-to-Shape (Containers) Transition with CSS and JavaScript - A Step-by-Step Guide

I am experimenting with creating a unique effect where two rectangular shapes, each containing text and with rounded ends, move towards each other, merge to form a single rounded rectangle as the page is scrolled down, and then separate back when scrolling ...

Creating a function generator using a string parameter in TypeScript

Is there a way to pass a string parameter to a function and retrieve an object with that key? function getFunction(name: string): { [name]: () => number } { return { [name]: () => { console.log(1); return 2; }, }; } const { m ...

Encountering a problem with controlling the number of splits allowed

I am encountering an issue with splitting my string using the code below. splitter.map((item1) => { let splitter1 = item1.split("=")[0].trimLeft(); let splitter2 = item1.split("=")[1].trimRight(); }); The content of item1 is as fo ...

Optimal methodologies for AngularJS components in content management system-based applications

Seeking the optimal approach for creating Angular 1 components with a CMS-driven strategy. My goal is to develop various label templates in a component-driven, highly reusable manner, fueled by CMS content. My plan is to utilize JSON as a component tree ...