Ordering and categorizing a JSON dataset

data = [
        {
            name: "Alpha",
            set: 5,
            weight: 185
        },      
        {
            name: "Alpha",
            set: 6,
            weight: 350
        },        
        {
            name: "Bravo",
            set: 2,
            weight: 185
        },        
        {
            name: "Charlie",
            set: 3,
            weight: 185
        },         
        {
            name: "Echo",
            set: 4,
            weight: 185
        }
]

I have a list of data objects which contain various attributes including the name and weight. My task is to filter this data based on the highest weight for each unique name. For instance, from the two objects with "Alpha", I need to select only the one with the greater weight (the second object). The challenge lies in filtering and reconstructing this data array while retaining the original values.

To facilitate visualizing all the data in a table, I must maintain the initial data array unchanged. However, I also need to create an additional array containing just the objects with the highest weight value for each specified name.

Answer №1

Utilizing lodash version 4 or higher is recommended for this particular task.

var sortedData = _.orderBy(entries, ['mass'], ['desc']);

By using the code snippet above, you can easily sort the data based on mass. After sorting, execute the following line of code: _.uniqBy(sortedData, 'label')

This will result in the final array containing unique elements.

var entries = [
        {
            label: "Alpha",
            group: 5,
            mass: 185
        },      
        {
            label: "Alpha",
            group: 5,
            mass: 350
        },        
        {
            label: "Bravo",
            group: 5,
            mass: 185
        },        
        {
            label: "Charlie",
            group: 5,
            mass: 185
        },         
        {
            label: "Delta",
            group: 5,
            mass: 185
        }
]

var sortedData = _.orderBy(entries, ['mass'], ['desc'])

_.uniqBy(sortedData, 'label')

Answer №2

My suggestion is to adopt a functional programming strategy:

let filteredRecords = records
    .filter(function(record) { 
        return records.find(function(innerRecord) {
            return innerRecord.name === record.name && innerRecord.weight > record.weight; }) === undefined;
     });

In this scenario, you will only keep records where there is no other record with the same name but higher weight. The resulting array of records is stored in filteredRecords, while keeping your original array untouched.

Answer №3

If you want to streamline your code, consider incorporating lodash instead of creating your own functions from scratch. For instance, if you need to sort an array by name, simply use the following snippet:

var data = [
    { name: "Alpha", set: 5, weight: 185 },
    { name: "Bravo", set: 5, weight: 350 },
    { name: "Charlie", set: 5, weight: 185 },
    { name: "Delta", set: 5, weight: 185 }
];

var sortedData = _.sortBy(data, ['name']);

Another scenario would be filtering based on both name and weight:

var filteredData = _.filter(data, {'name': 'Alpha', 'weight': 350});

Answer №4

This code snippet demonstrates a technique to sort items first by name and then by weight, filtering out duplicates based on the first occurrence of each item.

var records = [{
    name: "Alpha",
    set: 5,
    weight: 185
  },
  {
    name: "Alpha",
    set: 5,
    weight: 350
  },
  {
    name: "Bravo",
    set: 5,
    weight: 185
  },
  {
    name: "Charlie",
    set: 5,
    weight: 185
  },
  {
    name: "Charlie",
    set: 5,
    weight: 200
  },
  {
    name: "Delta",
    set: 5,
    weight: 185
  }
]

console.log(
  records.sort((a, b) => {
    if (a.name === b.name) {
      return a.weight >= b.weight ? -1 : 1
    }
    return a.name > b.name ? 1 : -1
  })
  .filter((rec, i, arr) => {
    if (i === 0) return true
    return rec.name !== arr[i - 1].name
  })
)

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

Function not activating with ng-keypress event

As a newcomer to AngularJS, I've been working on implementing ng-keypress events in my project. Despite referring to various blogs and following the instructions provided, it seems like my code is not functioning as expected! <div ng-app="myAp ...

Should I assign functions to services and app-wide variables to factories in relation to angular?

Imagine having the following scenario: factory var currentRecordId controller $scope.currentRecord = MyService.getCurrentRecordById(MyFactory.currentRecordId) service //define getCurrentRecordById My approach is to use factories for holding variabl ...

Mastering the comprehension of JSON objects with jQuery by transferring data via AJAX requests

I recently encountered a challenge where I had to work with an array of values and then convert it to JSON in order to insert it into an attribute. Here's what the code snippet looked like: <div data-categories="[[{"id":"4123","name":"Sushi Restau ...

Leveraging Python for JSON Operations

Upon running this code, an error occurred: Traceback (most recent call last): File "/Users/ccharest/Desktop/PCC/remember_me_2.py", line 7, in <module> username = json.load(f_obj) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/py ...

Data not being properly set in the form

Check out this chunk of HTML code: <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> <script> function getCords(){ ...

What specific circumstances make Avro a better choice than Json?

As I utilize Avro to feed data into my Kafka system, I find myself pondering the reasons behind Avro's creation and in which scenarios it would be more advantageous to use Avro over Json. Could it be true that Json is best suited for internet communi ...

Managing information from various selection fields

I am trying to work with a multiple select field in HTML that looks like this: <select name="deductions[]" multiple="multiple"> <option>Option 1</option> <option>Option 2</option> <option>.......</option> </sel ...

Creating a direct connection between a parent node and all of its children in OrgChartjs

Can I connect all children directly to one parent in Balkan OrgChart.js? This is my starting point based on the documentation of OrgChart.js. window.onload = function () { OrgChart.templates.family_template = Object.assign({}, OrgChart.templates.ana); ...

Utilizing jQuery to Adjust Tab Transparency

I'm trying to add some opacity to my jQuery tabs, but so far I've only been successful with accordions. Any tips or tricks for achieving this effect with tabs? Styling with CSS .ui-tabs{ background-image: none; background: rgba(204, 204 ...

Loading complex models with Three.js

Whenever I attempt to load a significantly large file utilizing the appropriate loaders provided by the library, the tab in which my website is running crashes. Despite trying to implement the Worker class, it doesn't seem to resolve the issue. Here i ...

Dealing with multiple select elements using jQuery when an option is chosen from each one

I am faced with a scenario where I have two select elements containing various options. My goal is to utilize jQuery to retrieve the values of these select elements only when valid options are selected. <div class="panel-heading"> <selec ...

Notify the parent component about the connectivity status of the children

I'm currently developing an application using React and Electron. One of the components I'm working on involves opening three TCP sockets and rendering children once all connections are established. Here's a simplified version of what it loo ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

What is the process for creating a button that can sort an array and count its elements?

I am having trouble creating a code that can sort products into alphabetical order and then count the number of items in the list within the same program. I have managed to write separate programs that achieve each of these tasks individually, but when I ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

Sending an array to unmanaged code and receiving it back without the need for duplication

Currently, I am working on creating a C# wrapper for my C++ library, and I am facing a challenge with passing arrays to unmanaged code and reading the results back in .NET. My goal is to have a wrapper function that can take an array of floats as input (m ...

The removeEventListener method in JavaScript fails to function properly

On my website, I have a unique feature where clicking an image will display it in a lightbox. Upon the second click, the mouse movement is tracked to move the image accordingly. This functionality is working as intended, but now I'm faced with the cha ...

Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option: <select runat="server" id="select"> <option value="A">White</option> <option value="B">Red</option> <option value="C">Yellow& ...

Assistance with utilizing Google Sheets scripts for retrieving formulas is needed

I've been working on a small search tool in Google Sheets as a personal project to improve my skills and knowledge of GS. Munkey has been guiding me over the past few weeks and helping me develop my understanding. Below are the links to my "Database" ...

Limiting the character count in a textarea can be achieved by implementing the 'jQuery InlineEdit' feature

Currently, I am utilizing the jquery.inlineedit.js plugin for inline editing, and one of my requirements is to limit the maximum length of text within the textarea. I have attempted to use other popular jQuery scripts for this purpose, but unfortunately, I ...