Arrange objects within nested arrays by their specific properties and then add a particular object to the end of the outer array within an object containing

I have an Object containing nested Arrays of Objects that I need to sort alphabetically by the "label" property and move the object with the label "other" to the end of each Array. I have a working solution, but I'm looking for a more streamlined approach. You can view my current solution on this JSFiddle link.

let things = {
  "animals": [{
      "id": 0,
      "label": "cat"
    },
    {
      "id": 100,
      "label": "Undefined"
    },
    {
      "id": 200,
      "label": "turtle"
    },
    {
      "id": 300,
      "label": "Other"
    },
  ],
  "colors": [{
      "id": 0,
      "label": "yellow"
    },
    {
      "id": 100,
      "label": "green"
    },
    {
      "id": 200,
      "label": "red"
    },
    {
      "id": 300,
      "label": "blue"
    }
  ]
}

let sortedThings = {};
Object.entries(things).forEach((entry) => {
  let key = entry[0];
  let otherOption = entry[1].filter((o)=> o.label === "Other");
  console.log(otherOption)
  let vals = entry[1].sort((a, b) => (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0)).filter((s) => s.label !== "Undefined")
  if(otherOption.length){
     vals = vals.filter((s) => s.label !== "Other");
     vals = vals.concat(otherOption);
  }
})

Answer №1

Here are some ways to enhance the optimization:

  1. Begin by excluding any instances of the "Undefined" value to prevent sorting delays.
  2. While sorting, explicitly designate "Other" as the higher-ranking element to shift it towards the array's tail end.

const things = {
  "animals": [{
      "id": 0,
      "label": "cat"
    },
    {
      "id": 100,
      "label": "Undefined"
    },
    {
      "id": 200,
      "label": "turtle"
    },
    {
      "id": 300,
      "label": "Other"
    },
  ],
  "colors": [{
      "id": 0,
      "label": "yellow"
    },
    {
      "id": 100,
      "label": "green"
    },
    {
      "id": 200,
      "label": "red"
    },
    {
      "id": 300,
      "label": "blue"
    }
  ]
};

const sortedThings = Object.entries(things).reduce((obj, [key, value]) => 
    (obj[key] = value
        .filter(item => item.label != "Undefined")
        .sort((a, b) => (
            a = a.label.toLowerCase(), 
            b = b.label.toLowerCase(), 
            a == b ? 0 : b != "other" && (a == "other" || a > b) ? 1 : -1
        )), 
        obj
    ), 
{});

console.log(sortedThings);

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

Deactivate the other RadioButtons within an Asp.net RadioButtonList when one of them is chosen

Is there a way to disable other asp.net radio buttons when one of them is selected? I have three radio buttons, and I want to disable the other two when one is selected. After doing some research, I managed to disable the other two when the third one is se ...

Can the Browser width/document width be maintained when shrinking the browser window size?

https://i.stack.imgur.com/a4gfA.pngLooking for a solution to maintain the browser/document width at 350px, preventing users from minimizing the window. The desired width is actually 400px, not 350px. Please refer to the image above. I require the window ...

Rails database is not properly embedding into Javascript when using as_json.to_json method. (results in "&quot" characters)

I have scoured nearly every SO past question without success. Within my main.html.erb file, I am mixing html/erb/javascript. (I understand it's not ideal, but I'm still grappling with asset pipelines and this is just a small project.) My goal i ...

javascript close the current browser tab

Can someone please help me with a JavaScript code to close the current window? I have tried the following code but it does not seem to work: <input type="button" class="btn btn-success" style="font-weight: b ...

Is it possible to change between universal and spa mode based on the query string?

Currently, I am working on a Nuxt.js application set to universal mode and deployed as a static website using nuxt generate. The app is pulling data from a GraphQL API linked to a CMS, and everything is functioning properly. Whenever content is updated in ...

Navigating through JSON object array using *ngFor directive in Angular 4

I am trying to iterate through an array of objects stored in my JSON file. JSON [ { "name": "Mike", "colors": [ {"name": "blue"}, {"name": "white"} ] }, { "name": "Phoebe", "colors": [ {"name": "red"}, { ...

Allow the response to be returned in the parent function by using the $.post method

I have a question regarding this particular code snippet: null. Why is the server_request function not returning the responseText as expected? And how can I modify it to achieve the desired outcome?</p> ...

The resolution of Q.all does not occur in the expected order

I'm currently facing an issue with the order in which promises are being executed in Node.js. The goal of the code is as follows: a) Run a query and use the resulting latitude/longitude pairs to b) Calculate the shortest paths (using an async funct ...

How can I set up an additional "alert" for each form when making an AJAX request?

let retrieveLoginPasswords = function (retrieveForgottenPasswords, checkLoginStatus) { $(document).ready(function () { $('#login,#lostpasswordform,#register').submit(function (e) { e.preventDefault(); $.ajax({ type: &quo ...

Need for input

I am working on organizing my routes in a separate file from app.js. The login route requires access to a Firebase instance. routes/auth.js var express = require('express'); var router = express.Router(); module.exports = function(firebase) { ...

Tips for effectively implementing a custom theme alongside a component library that utilizes Material UI without the need to apply it to every single component

What is the correct way to utilize a custom theme with a component lib that utilizes Material UI without wrapping every single component? import { createMuiTheme } from '@material-ui/core/styles'; const theme = createMuiTheme({ palette: { ...

Unable to assign a value to a constant within the class constructor

I'm aware that in TypeScript, readonly properties can only be assigned a value within a class constructor. However, I encountered an error while trying to do so inside the constructor of my class, specifically related to an array method handler. class ...

What is the best approach for creating a basic test to evaluate the functionality of MatDialog in Angular 2?

I'm currently working on a component that looks like this: @Component({ selector: 'my-form', templateUrl: './my-form.component.html', }) export class MyFormComponent implements OnInit { @Input('company') company: ...

Vue.js - encountering an issue with undefined response data

Greetings! I've encountered a script issue while trying to submit a form in VUE. The error message displayed in the developer panel states: "TypeError: error.response.data.errors is undefined". As a newcomer to Vue, I'm seeking some assistance as ...

Updating the PHP array index [0] to [a-custom-name]

Could you please review the array below? Array ( [0] => Array ( [fee_id] => 15 [fee_amount] => 308.5 [year] => 2009 ) [1] => Array ( [fee_id] => 14 [fee_amount] => 308.5 [year] => 2009 ...

Styling Process Steps in CSS

Just starting out with CSS! I'm looking to replicate the Process Step design shown in the image. https://i.stack.imgur.com/Cq0jY.png Here's the code I've experimented with so far: .inline-div{ padding: 1rem; border: 0.04rem gray ...

Interactive table with dynamic data retrieval

I need help displaying data dynamically from a datatable using an API. The API I am working with is located at this URL and I am utilizing the bootstrap4 datatable. You can also find my code on this JSFiddle. Can someone provide guidance or an example on h ...

determining the mean of randomly generated whole numbers within a list

I'm looking to create a certain number of random integers within a specified range set by the user (for example, generate 12 numbers between 10 and 20), and then find the average of those numbers. My issue is that when I request 10 numbers, it only ge ...

What is the reason behind the inconsistent behavior of Javascript's Date.getDate() and .setDate() methods?

As a hobbyist coder, I'm facing a challenging problem with building a dynamic HTML/CSS calendar. My goal is to have cells filled in based on today's date. However, when I attempt to add days to fill in another 13 days by looping through HTML elem ...

What is the significance of using the "why" in the href property within the

I need help understanding why the plus "+" is used before and after myUrl in the function .not. Even though it works fine with or without the +, I am curious about why it was included in the code snippet. <script type="text/javascript"> $(documen ...