A function that can retrieve distinct values for a specific property within an array of objects while maintaining their original order

Here is some information I have:

$scope.Reports = [
  { Id: 1, Name: 'Report One', Year: 2016, Month: 5 },
  { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 },
  { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 },
  { Id: 4, Name: 'Report Moon', Year: 2015, Month: 5 },
  { Id: 5, Name: 'Report Sky', Year: 2015, Month: 2 }
];

$scope.desc = function (arr) {
            return $('min')
              ($('map')(arr, '-Year'));
        };

I am attempting to extract the list of Year values in descending order, which will be used with an orderBy filter in AngularJs.

Given the above data, I wish to obtain [2016, 2015].

Can anyone guide me on how to achieve this?

Answer №1

While I'm not sure about any specific Angular features for this task, in JavaScript, it's quite simple: First, find the distinct years and then arrange them in descending order.

Here is an example that accomplishes this by creating an object with year keys:

var data = [
 { Id: 1, Name: 'Report One', Year: 2016, Month: 5 },
 { Id: 2, Name: 'Report Core', Year: 2016, Month: 5 },
 { Id: 3, Name: 'Report Alpha', Year: 2016, Month: 3 },
 { Id: 4, Name: 'Report Moon', Year: 2015, Month: 5 },
 { Id: 5, Name: 'Report Sky', Year: 2015, Month: 2 }
];
var years = retrieveUnique(data, "Year").sort(function(a, b) {
  // Numerically sorts in descending order
  return b - a;
});

function retrieveUnique(array, prop) {
  var obj = Object.create(null);
  array.forEach(function(entry) {
    obj[entry[prop]] = true;
  });
  return Object.keys(obj);
}

// Displaying the result
document.body.innerHTML = JSON.stringify(years);

I extracted the retrieveUnique function in case you need to apply it to similar scenarios.

In an ES2015 setting, you might opt for using a set instead of an object (and arrow functions).

Answer №2

Learn how to utilize loadash with Angular framework.

_.reverse(_.sortedUniq(_.map(dataArray,'Year')))

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

Nextjs is having trouble loading the Infogram script

Struggling to insert an Infogram into my project by pasting the script but it's not working as expected. All other scripts in _app.js are functioning properly, however, this particular script isn't loading the graphic even though it appears when ...

The complexities of stopPropagation() causing further confusion

I have encountered an issue with my code. It currently allows a dropdown functionality for a <ul> element, but when a child <li> is clicked, it also closes other menus of the same type. To fix this, I used an if clause to check if the clicked ...

Synchronize data with Microsoft AJAX using force sync

When working with the Microsoft AJAX framework, I encounter a problem where my AJAX calls are asynchronous when I actually need them to be synchronous. I'm struggling to find a solution for this issue. In addition, I have been having difficulty findi ...

Enhancing Performance of D3 JS for Visualizing Large XML Data

I am working on visualizing a large XML file, almost 1 GB in size, as a graph of nodes and links using D3 Javascript. I am currently working with mac 10.5.8. I have successfully extracted the content of the file, displaying it as: [Object Element]. The p ...

What's the best way to include CSS and Javascript in an HTML document?

I'm still getting the hang of CSS and JavaScript. I stumbled upon a cool countdown timer that I'd like to incorporate into my website, but I'm not quite sure how to place it where I envision it. Check out the timer here CSS: html,body{mar ...

the sizing issue with three div elements

I am attempting to create 3 parallel divs in HTML. The middle div should be exactly 960px wide and centered on the page, with the left and right divs positioned on either side. The minimum width of the page is set to 1024px. When the browser width exceed ...

Using Jquery to change an id with the .attr method may not always produce the desired results

I have a div element that functions as a button when clicked, with the ID of knight. Every time I click on any of the 3 buttons (including knight), it changes the ID of knight to elf (yes, I'm creating a game). I have a hover effect for knight usi ...

Struggling to toggle the visibility of a table with a button - successfully hiding it, but unable to make it reappear?

I need a button that can toggle (show/hide) a table. Currently, my code hides the table successfully, but it fails to show the table again when I click the button. It seems like there is an issue with refreshing or redirecting after clicking the button for ...

Having trouble making a call to my RESTful service from an AngularJS application using $http

I am having trouble with reading JSON data from a REST webservice using AngularJS $http. I have a simple REST webservice located in a separate project which returns JSON. However, when I attempt to access the REST service from Angular, it results in an err ...

What is the best way to ensure my php variable is easily accessed?

Recently, I've been working on implementing a timer and came across the idea in a post on Stack Overflow. <?php if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username'])) { //secondsDif ...

Effortlessly saving money with just one click

I have a search text box where the search result is displayed in a graph and then saved in a database. However, I am facing an issue where the data is being saved multiple times - first time saves properly, second time saves twice, third time three times, ...

JavaScript: Exploring Content Inside Headers

Using document.body.innerHTML allows you to search within the body of a webpage. Is there an equivalent method for searching within the "Head" section? I've been looking around but so far, I haven't come across any such function. ...

What is the best way to simulate DynamoDB promise functionality with Jest?

Looking for a solution without using any libraries (as they haven't worked in my case). How can I make it work for that promise returned by the dynamodb query? Check out the code to be tested below: const isUrl = require('is-url'); const ...

Is hard coding permissions in the frontend considered an effective approach?

I'm in the process of creating an inventory management system that allows admin users to adjust permissions for other employees. Some permissions rely on others to function properly, and I need to display different names for certain permissions on the ...

data retrieval not refreshing sorting post construction

My challenge involves fetching data from MongoDB with sorting. While it works perfectly on the development server, it fails to update the data after being built and hosted. import Review from "@/models/review"; import connectdb from "@/util/ ...

It is not possible to use Date.now within passport.js

When creating a user via Facebook on my Node.js website using passport, I want to assign the register date. In my Mongoose Schema, I can use the following for the local provider: regisDate: { type: Date, default: Date.now }, However, when it co ...

Exploring the angular js repeater component's context menu options

In one of my current projects, the client has specifically requested a right-click menu feature. However, the challenge lies in ensuring that the function triggered by the menu options has access to relevant information from the model. For instance, you ...

Trigger the script upon clicking the Save button within the AdminBro Edit page

AdminBro's documentation mentions that they provide predefined actions Edit (record action) - update records in a resource They also offer a hook called after. I created a function and assigned it to MyResource.edit.after. However, the issue is tha ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...

Ensuring compatibility of peerDependencies through devDependencies in npm3

With the recent update to NPM 3, automatic resolving of peer dependencies has been removed. This poses a challenge when developing a plugin/library for consumption by another application. If the underlying library uses peerDependencies, it requires manual ...