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

Receiving an inaccurate value from the input with type='number' attribute

There is an input field where users can enter a string, and I need to capture the value entered into it. $("#test").on("change", function(){ console.log($(this).val()); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery ...

Transfer and transform numerous arrays between Android and PHP server

Being new to Android, I am struggling with converting this array into a JSON array and sending it to the PHP server: {"menu":[{"id":"2","number":"3"}, {"id":"6","number":"4"}, {"id":"5","number":"6"}], "user":[{"uid": "12345","number":"<a href="/cdn- ...

"Error message: Undefined index error when trying to decode JSON

In my database, there's a JSON file named articles.json which contains data as follows: { "articles": [ { "id": 1, "title": "a" } ] } Now, I have written a script to decode this JSON file: <?php include "inc/header. ...

Integrating Amazon external images in NextJS

There is a specific issue with loading images from a URL stored on Amazon S3 within the domain configured in next.config.js. Strangely, when using external URLs like Unsplash, the images load fine. The problematic URL is: idinheiro-admin-images.s3.sa-east ...

Customize the appearance of a React component depending on its unique identifier

After creating a simple TODO app with drag and drop functionality, I am now looking to apply a line-through CSS style to any task added or dragged into the second column of my app. What is the best way to target these tasks using their unique ID: <div c ...

Move the Div element up and down when clicked

When a tag is clicked, the corresponding div opens and closes. I would like the div to slide down and up slowly instead of appearing immediately. <a href="" class="accordion">Click here</a> <div class="panel" id="AccordionDiv"> ...

Creating a personalized and versatile table component with unique functionality: where to begin?

Looking to create a versatile table component that can adapt for both desktop and mobile versions. If the screen width is below 720px, it should display a table using div, ul, li elements with a "load more" button at the bottom. If the screen width i ...

Optimizing Your HTML/CSS/JavaScript Project: Key Strategies for Modular

When it comes to web frontend projects (html/css/javascript), they are often perceived as more complex to read and maintain compared to Java/C#/C/C++ projects. Is it possible to outline some optimal strategies for enhancing the readability, modularizatio ...

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

Real-time array filtering with ReactJS for nested arrays

I am currently working on implementing a real-time filtering search feature for a lengthy list of items. The items are structured in the form of an array containing arrays with a string and an object, as shown below: const items = [ ["cats", [ ...

"Waiting for a promise in an Angular application while executing an SQLite insert

Currently, I am facing a challenge where I need to insert multiple rows into the database using the code snippet below: dataFactory.insertData = function (responseData) { var q = $q.defer(); var rows = 0; $.each ...

Error: PHP is showing an undefined index error when trying to decode JSON, even though the value

I am feeling quite puzzled. I transferred a key value pair object from jQuery to PHP and successfully alerted it back out. However, when I visit the PHP page, it indicates that the data is either null or an undefined index. Here is my jQuery code: $(&ap ...

ES6 Update: Manipulating Nested Arrays with JavaScript

I have the following list of items: [ { idItem: "1", name: "apple", itemLikes: [{ id: "1", idItem: "1" }] } ] My goal is to simply add a new object to the itemLikes array. Here is my ...

Struggling to retrieve unpredictable data in a Vue.js component

Help! I'm trying to randomly display one of these names in my HTML, but I can't seem to make it work: Vue.component('modal', { template: '#modal-template', data: { items: [ { name: 'Elena' }, { na ...

Encountered an Unpredictable SyntaxError: Is this a Cross-Domain Problem?

I have been attempting to connect with the Indian Railway API using Ajax in order to retrieve data in JSON format. Below is the code I am using: <!DOCTYPE> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleap ...

Selecting an option in Angular will only send the value ID

I am attempting to utilize ngOptions in Angular. My goal is to pass a parameter to the back-end that sends only the value, not the entire object. Below is my code: <div class="form-group"> <label>Parent Menu</label> <select class ...

Issues with Vercel's JavaScript Environment Variables Accessibility

I am encountering an issue trying to access environment variables on Vercel using JavaScript (TypeScript). Despite setting them under /settings/environment-variables, I receive undefined when attempting to access them with process.env.TURSO_DATABASE_URL du ...

A guide on cycling through the data within the input fields

Here's my code snippet: <div class="form-group row text-right" *ngFor='let row of vipInput'> <label class="col-sm-3 form-control-label m-t-5" for="password-h-f"></label> <div class="col-sm-9 form-control-label m-t-5 ...

Creating a Controlled accordion in Material-UI that mimics the functionality of a Basic accordion

I'm a Junior developer seeking assistance with my first question on this platform. Currently, I am working with a Controlled accordion in React and need the icon to change dynamically while staying open even after expanding another panel. The logic ...

What are the steps for implementing if-else statements in JavaScript when working with multiple dropdown lists?

I have encountered an issue while trying to display options in multiple drop-down lists. Only two words (CHENNAI AND IOS-XE, BANGALORE AND IOS-XR) are being displayed and the rest of the words are not appearing. Can someone provide assistance on fixing thi ...