Filter array to only include the most recent items with unique names (javascript)

I'm trying to retrieve the most recent result for each unique name using javascript.

Is there a straightforward way to accomplish this in javascript? This question was inspired by a similar SQL post found here: Get Latest Rates For Each Distinct Rate Name

My current approach involves creating an array of distinct names, filtering results for each name, sorting those results in descending order by date, and then adding the first entry to a new array. However, it feels quite complex.

Here is an example array:

[{"name": "John", "points": "400", "date": "2011-01-05"}
{"name": "John", "points": "410", "date": "2011-06-31"}
{"name": "Jane", points": "147", "date": "2011-09-21"}
{"name": "Jack", "points": "68", "date": "2011-07-14"}
{"name": "Jack", "points": "100", "date": "2011-10-30"}]

The desired output should resemble this:

[{"name": "John", "points": "410", "date": "2011-06-31"}
{"name": "Jane", points": "147", "date": "2011-09-21"}
{"name": "Jack", "points": "100", "date": "2011-10-30"}]

Answer №1

To organize the data effectively, begin by arranging it in descending order according to dates, then filter out duplicates:

const information = [{
        "name": "John",
        "points": "400",
        "date": "2011-01-05"
    }, {
        "name": "John",
        "points": "410",
        "date": "2011-06-31"
    }, {
        "name": "Jane",
        "points": "147",
        "date": "2011-09-21"
    }, {
        "name": "Jack",
        "points": "68",
        "date": "2011-07-14"
    }, {
        "name": "Jack",
        "points": "100",
        "date": "2011-10-30"
    }
];

data.sort((a, b) => new Date(b.date) - new Date(a.date));

const uniqueData = information.reduce((accum, record) => {
    if(!accum.find(entry => entry.name === record.name)){
        accum.push(record);
    }
    return accum;
}, []);

console.log(uniqueData);

Answer №2

To add or update the elements in a fresh array, follow these conditions:

  1. If the item is not present in the new array (Add)
  2. If the item is already there and the existing item's date is older (Update)

const data = [
  { name: "John", points: "400", date: "2011-01-05" },
  { name: "John", points: "410", date: "2011-06-31" },
  { name: "Jane", points: "147", date: "2011-09-21" },
  { name: "Jack", points: "68", date: "2011-07-14" },
  { name: "Jack", points: "100", date: "2011-10-30" }
];

const latest = [];
for (let item of data) {
  const found = latest.findIndex(l => l.name === item.name)
  if (found !== -1) {
     if(item.date > data[found].date) {
         latest[found] = item; // update
     }
     continue;
  }
  latest.push(item); // add new
}

console.log(latest);

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 only the date in bootstrap-datetimepicker

I am currently utilizing the repository created by smalot, and my intention is to choose and display dates only (while in other instances I showcase both date and time, hence utilizing this repository). Although I have succeeded in selecting dates only, th ...

A highly effective method for nesting items within a list through recursive functions

I am currently in the process of developing my own commenting system because I have found that existing platforms like Disqus do not meet my specific needs. My backend is built using NodeJS and MongoDB, and I need to execute two primary queries on my data ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...

Guide on developing and releasing a Vuejs component on NPM

I have been diving deep into vue lately and incorporating it into all of the projects at my workplace. As a result, I have developed various components, particularly autocomplete. Although there are plenty of existing options out there, none seem to fulfil ...

Exploring Objects within an Array in Ionic 2 and AngularJS 2

I am currently working on displaying reviews obtained from a Laravel API, showcasing feedback on various meals. The goal is to create a slideshow of review messages along with additional data as presented in the array of Objects below: { "2": { ...

Encountered issue: The type 'Teacher[]' cannot be assigned to the type 'Teacher'

I am currently working on enhancing my angular application by adding a new service. However, I have encountered an error that I need help fixing: The error message states: Type 'Teacher[]' is not assignable to type 'Teacher'. Property ...

Develop a circular carousel using React JS from scratch, without relying on any third-party library

I am looking to replicate the carousel feature seen on this website. I want to mimic the same functionality without relying on any external libraries. I have found several resources explaining how to achieve this. Most suggest creating duplicate copies o ...

When running through Selenium web driver, JS produces inaccurate results

Currently, I am utilizing JavaScript to determine the number of classes of a specific type. However, when I run the JS code in Webdriver, it provides me with an incorrect value. Surprisingly, when I execute the same JavaScript on the Firebug console, it gi ...

The useEffect hook is triggering multiple unnecessary calls

Imagine a tree-like structure that needs to be expanded to display all checked children. Check out this piece of code below: const { data } = useGetData(); // a custom react-query hook fetching data from an endpoint Now, there's a function that fin ...

What is the right way to send a success response from Express JS to Backbone when logging out a user?

I'm currently learning how to work with Express JS and Backbone. On the server side using Express.js, I have this code snippet for logging out a user: app.get('/logout', function(req, res) { req.logout(); res.send('How can I ...

Prevent duplicate components from interacting with one another in Angular

My Tabs component has its own variables and functions, and it works perfectly. However, I encountered an issue when trying to place multiple tab components on the same page. Whenever I change the value of one tab, it also affects the other tab component. ...

Transform a collection of objects into instances of a class

I have a scenario where I am fetching an array of objects from PHP and my goal is to transform this data into instances of a class called ContentData. The current solution that I have seems to work fine, but deep down I sense that there might be a more el ...

Is your JavaScript function failing to execute properly?

Within my script, I have defined two JavaScript functions: myFunction() and submitForm(). <script> var intervalID = 0; function myFunction(interval) { if(interval == 1) { if(intervalID != 0) { window.clearInterval(intervalID); in ...

Svelte remains static and is not experiencing re-rendering

I am currently incorporating the history component in Svelte, where it should display when changes occur in the bids array. const bidsArray = [ { player: 0, bidType: 'pass' }, { player: 1, bidType: 'level', level: '1&apos ...

AngularJS: Modifying directive according to service value update

In my current application, I have a basic sidebar that displays a list of names fetched from a JSON call to the server. When a user clicks on a name in the sidebar, it updates the 'nameService' with the selected name. Once the 'nameService& ...

Error encounter in JSP is nested within another JSP file, both of which utilize jQuery

Before proceeding, it is important to note that I am in the process of selecting a month using a datepicker and a specific meter (by its serial number). Once this information is selected, a query will be sent to a MySQL database to retrieve data for plotti ...

How to include a for loop within an array as an element

Below is an illustration of the data available: $scope.allmovies[ {title:"Harry Potter", time:130}, {title:"Star Wars", time:155}, {title:"Lord of the Rings", time:250}, {title:"Goonies", time:125}, {title:"Fast and Furious", time:140} ]; var mostpopular ...

Is there a way to prevent future dates from being selected on angular p-calendar?

I need help with disabling future dates in a calendar datepicker input field. Here's how I'm currently using it: <p-calendar maxDate="dateTime" showTime="true" hourFormat="12" showButtonBar="true" [(ngModel)]="dateTime" name="timeOfUse" requ ...

Displaying a checklist that shows all items that have been selected, rather than only showing the first selected item

I'm facing an issue with my data table that has checkboxes corresponding to each row. My goal is to append the contents of the selected rows into a "Favorites List" when the checkbox is clicked. However, I am currently only able to display the content ...

Disable the functionality of the next and previous buttons for the Bootstrap carousel when clicking on the outer

Here is the code for the carousel: The next/prev button functions under its respective div, how can I stop it? When I click on the div below the carousel, the carousel continues to move as usual. Below the carousel div, there is another one with a tabbi ...