What is the best way to arrange an array of objects based on a specific condition

I have an array of objects that contain properties.

My goal is to sort them by status in a specific order: 15, 17, and then 16 using JavaScript.

In this array of objects, any object with a status value of 16

should be placed at the end, while the rest should be sorted in ascending order based on the status property.

How can I achieve this in JavaScript?

var result = arrobj.filter(e => e.details.status !== 16).sort((a, b) => a.status - b.status);

var arrobj = [
  {
    "id":1,
    "name":'xyz',
    "details": {
    "job": 'fulltime',
    "status": 15
    }
  },
  { 
    "id":2,
    "name": 'abc',
    "details": {
    "job": 'partime',
    "status": 16
    }
  },
  { 
    "id":3,
    "name": 'zen',
    "details": {
    "job": 'fulltime',
    "status": 17
    }
  },
  { 
   "id":5,
    "name": 'abu',
    "details": {
    "job": 'fulltime',
    "status": 16
    }
  },
{ 
   "id":7,
    "name": 'john',
    "details": {
    "job": 'parttime',
    "status": 15
    }
  },
 { 
   "id":10,
    "name": 'jocob',
    "details": {
    "job": 'fulltime',
    "status": 17
    }
  }
]

Expected Output

[
  {
    "id":1,
    "name":'xyz',
    "details": {
    "job":: 'fulltime',
    "status": 15
    }
  },
 { 
   "id":7,
    "name":'john',
    "details": {
    "job":: 'parttime',
    "status": 15
    }
  },
  { 
    "id":3,
    "name":'zen',
    "details":: {
    "job":: 'fulltime',
    "status": 17
    }
  },
 { 
   "id":10,
    "name"': 'jocob',
    "details":: {
    "job":: 'fulltime',
    "status": 17
    }
  },
  { 
    "id":: 2,
    "name"::~ 'abc",
    "details"::~ {
    "job"~~: 'partime',
    "status": 16
    }
  },
  { 
   ~'id": 5,
    ~'name":~ 'abu',
    ~'details"": {
    ~~'job"": 'fulltime',
    ~~'status''':' 16
    ~}
  }
]


Answer №1

To create custom sorting rules, we can utilize the compareFn parameter within the Array.prototype.sort(compareFn) method.

For example:

var sortedResults = arrayObjects
    .sort((firstObj, secondObj) => {
        let x = firstObj.data.type
        let y = secondObj.data.type
        if (x === 14) x = Number.MAX_SAFE_INTEGER
        if (y === 14) y = Number.MAX_SAFE_INTEGER
        return x - y
    })

Answer №2

const orderedResults = [...objectArray.filter(obj => obj.details.status !== 16).sort((a,b) => a.details.status - b.details.status), ...objectArray.filter(obj => obj.details.status === 16)]

Are you referring to this code snippet?

Answer №3

ES5 Solution

 arrObjects.sort((first, second) => {
     if (first.info.state === 16) {
         return 1;
     } else if (second.info.state === 16) {
         return -1
     } else {
         return first.info.state - second.info.state
     }
  })

Answer №4

In the latest version of EcmaScript, Array.sort has been updated to be stable. This means that you can divide complex sorting tasks into two steps - first by status, and then by moving all items with a status of 16 to the end. However, this may not be the most efficient solution.

arrobj.sort((first, second) => first.details.status - second.details.status)
      .sort((first, second) => (first.details.status === 16) - (second.details.status === 16));

Answer №5

This code snippet can also be used for your specific situation. You were almost there!

arrobj.filter(element => element.details.status !== 16).sort((x, y) => {return x.details.status - y.details.status}).concat(arrobj.filter(element => element.details.status == 16));

Answer №6

Your previous implementation of the sort function needs revision. Here is an improved version that also allows for changing the sort order.

// Function to sort by status
function sortByStatus(array, asc = true) {
  let newArray = [...array];

  // Filter and sort based on status
  if (asc) {
    newArray = newArray.filter(e => e.details.status !== 16).sort((a, b) => a.details.status > b.details.status && 1 || -1);
  } else {
    newArray = newArray.filter(e => e.details.status !== 16).sort((a, b) => a.details.status < b.details.status && 1 || -1);
  }

  return newArray;
}

// Merge the sorted result
const arrobj = [{
    "id": 1,
    "name": 'xyz',
    "details": {
      "job": 'fulltime',
      "status": 15
    }
},
{
    "id": 2,
    "name": 'abc',
    "details": {
      "job": 'partime',
      "status": 16
}
...
];

const result = [...sortByStatus(arrobj), arrobj.filter(e => e.details.status === 16)];

var arrobj = [{...}];  // Array object containing data omitted for brevity

function sortByStatus(array, asc = true) {
  let newArray = [...array];

  if (asc) {  // Sorting in ascending order
    newArray = newArray.filter(e => e.details.status !== 16).sort((a, b) => a.details.status > b.details.status && 1 || -1);
  } else {  // Sorting in descending order
    newArray = newArray.filter(e => e.details.status !== 16).sort((a, b) => a.details.status < b.details.status && 1 || -1);
  }

  return newArray;
}

const result = [...sortByStatus(arrobj), arrobj.filter(e => e.details.status === 16)];
console.log(result);

Answer №7

One way to ensure that objects with status 16 are placed at the end of your array is by including .status in the sorting function sort(). To achieve this, I created a separate array specifically for objects with the status of 16 and then appended it to the end of the original array containing all other objects.

var sortedArray = originalArray.filter(item => item.details.status !== 16)
                                .sort( (a, b) => a.details.status - b.details.status);
sortedArray = sortedArray.concat(originalArray.filter(item => item.details.status === 16));

console.log(sortedArray)

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

How can I retrieve elements i from each array in HandlebarsJS and then access element j, and so on?

Given a JSON like this: { "network": [ { "name": [ "John", "Jill", "June" ] }, { "town": [ "London", "Paris", "Tokyo" ] }, { "age" : [ "35", "24", "14" ] } ] } Unfortunately, my data is in this format and I have to work w ...

Convert several arrays into a PHP object

I've been struggling for a few hours trying to figure out how to accomplish this task. I currently have an array structured like so: array (size=2) 0 => array (size=14) 'NR COMANDA' => string '251729' (length=6) ...

The "Boostrap Confirmation" plugin in JQuery fails to appear upon the second click

After changing the confirmation method from an MVC Action to an Ajax method, I noticed that the confirmation box does not appear when clicking a second time. It seems to have stopped working possibly because the page is no longer being refreshed. How can ...

A recursive function enhanced with a timeout mechanism to avoid exceeding the stack call limit

Trying to search for images on any object of various depths using a recursive function can lead to a Maximum call stack size exceeded error in certain cases. A suggested solution here involves wrapping the recursive function in a setTimeout, but this seems ...

Turn only one bracket on the accordion

When clicking on a specific header, I want only one chevron to rotate instead of all the chevrons rotating. I am currently unsure how to specify which chevron should rotate individually. My project is in ASP.NET MVC 5 and I am using razor view to loop th ...

The use of 'process.argv' and 'process.argv.slice(1)' does not seem to be functioning properly within Cypress

Currently, I am utilizing Cypress with JavaScript for my automation testing needs. My current task involves storing the user-passed command to run a script. Allow me to elaborate: Below is an excerpt from my package.json file: "scripts": { &q ...

Why am I unable to locate my personalized module?

I've encountered an issue with my npm module not being found in my sample script after publishing it. Here is the link to my module: https://www.npmjs.com/package/kong-hmac https://github.com/y-zono/kong-hmac-js Here's what I have tried: $ m ...

Tips for accessing an Angular service from different Angular controllers

I am a beginner with angular js and I am currently exploring ways to call the service provided in the code snippet below from a controller. The service is defined as follows. app.factory('myappFactory', ['$http', function($http) { v ...

The element type provided is not valid: it should be a string (for built-in components) or a class/function. Utilizing SSR with Node.js, React, and React-

Playground: https://codesandbox.io/s/focused-dream-ko68k?file=/server/server.js Issue Error: Encountered an error stating that the element type is invalid. It was expecting a string or a class/function, but received undefined instead. This could be due ...

Utilize Vue to localize the click events of buttons on the webpage

I have a scenario where I have several buttons on a page, and when I click one to toggle its text, all of the buttons change. How can I utilize VUE to isolate functionality and make each button's @click event only affect the clicked button? In the cod ...

The React-FontAwesome icon is unable to display when a favicon has been set

I encountered an issue while using the react-fontawesome module to display brand icons. Whenever I set a favicon in <Head>...</Head> (imported from next/head), all the react-fontawesome icons disappear. Can someone please advise me on how to re ...

Attempting to retrieve an array within a Mustache JavaScript template

I'm attempting to retrieve data from a mustache array using this.location.coordinates.0: <div class="block"> <label>Location (longitude/latitude):</label> {{location.coordinates.0}}/{{location.coordinates.1}} </d ...

Dynamically insert JavaScript and CSS files into the header by using the append method

Due to a specific reason, I am loading CSS and scripts into my head tag using the "append" method. For example: $("head").append('<script type="application/javascript" src="core/js/main.js"></script>'); I'm asynchronously pulli ...

What is the method for sending a multipart request using request.js?

I'm stuck on how to send multiple fields via multipart. I know there's a solution using https://github.com/felixge/node-form-data I have all the necessary fields ready and just need to send them as multipart to work with the async result... If ...

Partial view remains stagnant despite successful ajax post completion

I am currently in the process of developing a system that will showcase uploaded images from a file input into a specific div within my view. (with intentions to incorporate document support in the future) The challenge I am facing is that the partial vie ...

PHP is automatically converting all of the float values in my array to integers

I am encountering an issue with the following code: $val = (float) $desc; if (!isset($runepage['statistics'][$key])) { $runepage['statistics'][$key] = (float) 0.0; } $runepage['statistics'][$key] += $val; Her ...

I need to ensure that every number in vector_total is unique and not repeated

To ensure that vector_total does not contain any repeated numbers. A function to input vector1 and vector2 declared in main. void enter_vectors(int vector1[], int vector2[], int vector_total[], int *n, int *m) { int i=0, j=0; /*Entering num ...

How can I switch the values of two select components in React js when clicked?

I am working on a project where I have two select components positioned on the right and left side respectively, each with different values - A on the right side and B on the left side. Now, in response to a button click event, I need to swap component A t ...

[Vue alert]: Issue with rendering: "TypeError: Unable to access property 'replace' of an undefined value"

I'm currently working on a project similar to HackerNews and encountering the following issue: vue.esm.js?efeb:591 [Vue warn]: Error in render: "TypeError: Cannot read property 'replace' of undefined" found in ---> <Item ...

Why am I receiving a null response from my ajax request?

I have a working ajax call to fetch XML data from my REST API. However, when I try to echo the results, JQuery returns null. If I use var_dump on the results instead, JQuery accepts the information but it's not formatted correctly and causes errors. ...