Arranging an array of objects based on dual criteria

Sorting an array of objects based on 2 conditions is my current challenge

  1. First, I need to sort by value
  2. If the names are the same, I want to display them next to each other in ascending order of their values

For a visual example, check out this demo: https://codesandbox.io/s/relaxed-dhawan-sfryng?file=/src/index.js

Answer №1

This is a detailed solution to the problem at hand. Take some time to review the code snippet provided below:

const array = [
  {
    name: "John",
    value: 5
  },
  {
    name: "David",
    value: 6
  },
  {
    name: "John",
    value: 2
  },
  {
    name: "Michael",
    value: 4
  }
];

const customSort = (data) => {
  
  // Logic explained in comments above
  
}

console.log(customSort(array))

Answer №2

Here is a solution that may be helpful:

const items = [
  {
    name: "Alice",
    value: 7
  },
  {
    name: "Bob",
    value: 3
  },
  {
    name: "Alice",
    value: 6
  },
  {
    name: "Charlie",
    value: 2
  }
];

const groupedItems = [];

// Find the index of an item by its name in the groupedItems array
const findIndex = (name) => {
  let index = -1;
  groupedItems.forEach((groupedItem, _index) => {
    if(groupedItem.name === name) {
      index = _index;
    }
  });
  return index;
}

// Group items by their name
const groupByName = () => {
  items.forEach((item) => {
    const name = item.name;
    const value = item.value;
    let index = findIndex(name);
    
    // Add the name to groupedItems if it hasn't been added before
    if(index === -1) {
      groupedItems.push({
        name: name,
        values: [],
        minValue: Infinity
      });
      index = groupedItems.length - 1;
    }
    
    // Add current value to the list of values
    groupedItems[index].values.push(value);

    // Update minValue
    if(groupedItems[index].minValue > value) {
      groupedItems[index].minValue = value;
    }
  });
}

groupByName();

// Sort by minValue and return the final objects
const finalResult = groupedItems.sort((a, b) => a.minValue - b.minValue).flatMap((item) => (
  item.values.sort((firstVal, secondVal) => firstVal - secondVal).map((val) => {
    return {
      name: item.name,
      value: val
    }
  })
));

console.log(finalResult);

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

Updating a Rails partial using JSON response from an AJAX post request

I recently implemented an AJAX post request in my backend Rails application to upload a file. Upon successful posting, the response contains a JSON list of files. Now, I face the challenge of reloading the file list on my 'detalhes.html.erb' vie ...

Leveraging Vue computed properties to update local state without the need for Vuex

I need help with filtering a list of people's scores based on different time periods. Each person has a 'scoreHistory' array containing their scores at various points in time, and I want to see the total score for each person starting from 0 ...

Using jQuery to reveal the following unordered list after an H3 element by sliding it

<h3>Details<span class="dropdown">View</span></h3> <div id="sbc"> <ul> <li><h2>Role: Supervisor</h2></li> <li>Manager Contact:</li> < ...

What is the best way to update the old string values with the new string values?

function decipher(str) { // YOU DID IT! var newString = str.split(" "); for(var x = 0; x < newString.length; x++ ){ for( var y = 0; y < newString[x].length; y++ ){ if(newString[x].charCodeAt(y) < 78){ String.fromCharCode(ne ...

Display a loading dialog for several asynchronous requests being made via AJAX

When making two asynchronous ajax calls, a loading dialog box is displayed for each call using the code below: jQuery('#msg_writter').show(); After a successful request, the loading dialog is hidden with the following code: jQuery('#msg_w ...

Delete one object and then sequentially rename all remaining objects

object This is the object I retrieved. How can I remove module_1 object and rename the module object? For example, remove module_1 and rename module_2, module_3... to module_1, module_2... `{ "module_1": { "modulename": "mat ...

Is it possible to show a pop-up window containing aggregated data when the jQuery double-click event

How can I create a pop-up window to display aggregated data when the Double-click event is triggered in jQuery? In my code, each questionId has multiple related reasons. When a user clicks or selects a questionId button/event, the selected questionId will ...

Exploring the Jquery functionality: $(document).ready(callback);

Hey there, I'm struggling to run a function both on window resize and document ready. The issue is that when the resize event is triggered by mobile scroll, it's essential to ensure the height hasn't changed. Oddly enough, the code works fin ...

Using ant-design with react-draggable for modals: A step-by-step guide

Trying to implement a modal window using ant-design with the react-draggable npm package has been quite challenging. For those unfamiliar, react-draggable is a simple component for enabling drag functionality on elements. However, I encountered an issue wh ...

Having trouble receiving a Java Response through Ajax when using dataType: "jsonp", but it works when using dataType: "text"

I am having trouble retrieving the Callback response value in ajax with the provided code snippet $.ajax({ type: 'POST', jsonpCallback: 'jsonCallback', contentType: 'application/json', url: apiurl, dataTyp ...

Embed the component into the array collection

I have an array and I want to display a random component inside it. Specifically, I want to include the FeedbackComponent before the last two objects in the array. This is how it should look like in a schematic representation: storyObject storyObject st ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

Grouping and retrieving values from an array of JavaScript objects

I am looking to implement a groupBy function on the object array below based on the deptId. I want to then render this data on a web page using AngularJS as shown: Sample Object Array: var arr = [ {deptId: '12345', deptName: 'Marketin ...

Dealing with HTML and Escaping Challenges in jQuery Functions

Here is a string I have: var items = "<div class='item'><div class='item-img' style='background-image: url('images.123.jpg')'></div></div>" I am looking to update the inner HTML of a div: $ ...

Misunderstanding the Variable Scope Concept in Node.js

I am struggling to comprehend why the return of an array from another function is confined to only one block of code. For example: exports.join = function(req, res){ User.findById(req.user._id, function(err, user) { var dupe = []; //placeholder arr ...

processing an array using ajax form submission

Trying to manage an array that is returned from a PHP file after submitting form data. The value of the data after form submission is = ARRAY but I am unable to use this array in any way. Any suggestions on how to handle this array? Javascript: $(&apo ...

Utilizing AngularJS, the method to retrieve the image source from text within a scope variable

In my current project, I have a scope variable that contains a segment of HTML code. Here's an example: $scope.htmlcode = '<img src="image-path/image-name.jpg" /> some plain text,some plain text text etc etc'; My goal is to display o ...

What is the best way to incorporate external scripts into a Node.js project?

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.js"></script> What is the process for adding an external library to a node.js application? I am seeking assistance on how to integrate the following library into my ...

Adding data to a JavaScript array with two dimensions

Having some trouble adding values to an array in JavaScript. I'm still new to this language. Below is the code: eventsArray = new Array(); $.each(xmlJsonObj.feed.entry, function(index, value){ eventsArray[index] = new Array('title' = ...

Tips for handling npm dependency issues

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6715020604134a1306004a0612130804080a170b021302275249524957">[email protected]</a> has requested a peer version of react@^15.0.0, but it is not currently installed on ...