Search through an array, identify duplicates, and transfer them into a separate array

I am working with an array of objects containing dates and I am looking to extract objects with the same date values into a new array. Below is the code snippet.

    var posts = [
  {
    "userid": 1,
    "rating": 4,
    "mood": "happy",
    "date": "2017-05-24T04:00:00.000Z"
   },
  {
    "userid": 1,
    "rating": 3,
    "mood": "happy",
     "date": "2017-05-24T04:00:00.000Z"
  },
  {
    "userid": 1,
    "rating": 3,
    "mood": "angry",
    "date": "2017-05-25T04:00:00.000Z"
  },
  {
    "userid": 1,
    "rating": 5,
    "mood": "hungry",
    "date": "2017-05-25T04:00:00.000Z"
  }]
var may25=[];

for(i=0;i < posts.length;i++){
if(posts[i].date === posts[i].date){
may25.push(posts[i].date)
}
}

Answer №1

To efficiently group items by date, one approach is to extract the date from a string and use it as a key for an object. This results in an object containing all the grouped items.

var data = [{ id: 1, value: 4, status: "open", timestamp: "2019-08-15T14:30:00.000Z" }, { id: 2, value: 6, status: "closed", timestamp: "2019-08-15T16:45:00.000Z" }, { id: 3, value: 5, status: "pending", timestamp: "2019-08-16T10:20:00.000Z" }, { id: 4, value: 3, status: "resolved", timestamp: "2019-08-17T09:10:00.000Z" }],
    groups = Object.create(null);
    
data.forEach(function (item) {
    var dateKey = item.timestamp.slice(0, 10);
    groups[dateKey] = groups[dateKey] || [];
    groups[dateKey].push(item)
});

console.log(groups);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Interested in finding May 25th dates specifically? Here's a solution:

var may25Dates=[];

for (i=0;i < posts.length;i++) {
    if (posts[i].date === "2017-05-25T04:00:00.000Z") {
        may25Dates.push(posts[i].date)
    }
}

Answer №3

If you are looking to organize your data, consider creating an object that stores date => event pairs :

var collection = items.reduce((obj, event) => ((obj[event.date] = obj[event.date] || []).push(event), obj), {});

Once you have your object set up, you can easily access specific events like this:

collection["2017-05-25T04:00:00.000Z"].forEach(console.log);

Here is a breakdown of how it functions:

items.reduce((obj, event) => ...) // loops through the items and passes each one as an event to the function along with an empty object

(obj[event.date] = obj[event.date] || []) // retrieves the array for the specific date or creates a new one if none exists

.push(event) // adds our event to the 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

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

Steps for correctly displaying a success message after clicking and copying to the clipboard:

In the process of developing a color palette, I am incorporating a clipboard icon enclosed in a Tooltip component alongside each color. The functionality involves copying the color's name to the user's clipboard upon clicking the icon. Subsequent ...

Best practice for sending a Facebook token securely between client and server

I'm facing a dilemma on how to securely transfer a user's Facebook token from their client to my server. Currently, I have the following approach in mind: The user accesses a webpage and logs in to Facebook; Facebook token is obtained; User&apo ...

Retrieve the HTML code from a webpage on a different domain

Looking to extract HTML from another domain. Attempted solution: $.get("http://website1.com", function(data) { alert("Data Loaded: " + data); }); (not working) For example, as the owner of two websites: website1.com website2.com Now, the goal is to ret ...

What is the method for determining the overall page load time of a website, taking into account the total loading time instead of just the document.ready()

I recently attempted to create a function using either JavaScript or Python with Selenium to measure the page load time of a website. While document.ready() gives me the DOM load time, it may not capture AJAX calls that occur afterwards. I noticed there i ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

Which names can be used for HTML form tags in jQuery?

Recently, I encountered an issue related to jQuery form serialization which stemmed from naming a form tag "elements". The problem arose when using jQuery $(’form’).serialize(). Here is an example of the problematic code: <form> <input name=" ...

Looking to duplicate the elements with the click of a button?

I am in need of assistance with my registration form. My goal is to move the elements contained within the <fieldset> tags to the end of a row when the user clicks the + button. The result you see initially has been recreated. Thank you for your s ...

guide on creating a simple line highchart using JSON data

Here is the JSON data I have: {"09/02/2014 15:36:25":[33.82,33.42,40.83],"08/11/2014 16:25:15":[36.6,33.42,40.45],"07/30/2014 08:43:57":[0.0,0.0,0.0],"08/12/2014 22:00:52":[77.99,74.1,80.12],"08/12/2014 21:19:48":[56.91,63.23,52.42],"07/23/2014 13:37:46": ...

input value does not change when the "keyup" event is triggered

I'm encountering an issue with the code below. The code is for a simple To Do app using Javascript. I followed a tutorial step by step, but my app isn't functioning as expected. When I press the enter key, the input value should be added to the l ...

Exploring the capabilities of the jQuery `val()` function alongside the dynamic framework

Whenever I have a JavaScript variable that contains HTML printed from a table on my server, I encounter issues when using it in a jQuery function like val(). The problem arises every time someone enters content with special characters like " or '. Thi ...

Simultaneously activate the 'onClick' and 'onClientClick' events on an ASP button using JavaScript

I have encountered an ASP button while working on existing code that has both onClick and onClientClick events attached to it. My goal is to trigger both events by generating a click event from an external Javascript file. The line of code I am using for ...

Sequelize JS - Opting for the On clause in join operations

Seeking guidance on selecting the appropriate ON clause for a join. I am working with two tables - packages and users. The package table contains two fields/columns (owner_id, helper_id) that serve as foreign keys to the same users table. My goal is to per ...

Node.js is great at hosting HTML files, but struggles when it comes to loading script files within those pages

Recently, I’ve been working on creating a simple login page using a mongoDB database along with Node.js and express. Since I'm still new to Node.js, I'm facing an issue that seems more complicated than it actually is. The main problem I’m en ...

How can I achieve a similar functionality to array_unique() using jQuery?

When I select values from a dropdown, they are stored as an array like ["1","2","3"] Upon each change, the code below is executed to generate a new array based on the selected values: $('#event-courses-type').on('change', function(){ ...

The second instance of a React Paginate on the same page remains static and does not trigger a

Having a bit of trouble with using react-paginate for pagination - I have two instances on the same page (one at the top and one at the bottom). When a new prop is received, only the top instance gets re-rendered. The code seems to be working fine as all ...

Passing a return value to ajax success within an Express application

I am trying to retrieve a value from an included file and use it in the success function of an ajax call within Express. Below is my code for app.js: var userdetail = { "useremail":req.body.useremail, "fname" : req.body.fname, "lname" : req.bo ...

The variable "$" cannot be found within the current context - encountering TypeScript and jQuery within a module

Whenever I attempt to utilize jQuery within a class or module, I encounter an error: /// <reference path="../jquery.d.ts" /> element: jQuery; // all is good elementou: $; // all is fine class buggers{ private element: jQuery; // The nam ...

Looking for Efficiency in Basic JavaScript Arithmetic Operations

I'm having trouble figuring out how to display a total price after a selection is made. My goal is to take the selected value, multiply it by 100, and then use the updateTotal function to show the total. // Gather Data & Prices for Updating Dynamic P ...