Sort an array of object by a property (with custom order, not alphabetically)

javascript sort array of numbers
javascript sort array of objects alphabetically
javascript sort object by value
javascript sort array of objects by property alphabetically
javascript custom sort
javascript sort array of objects by key
angular 6 sort array of objects by property
javascript sort array of objects by key value

I would like to get your help about this little problem.

I have like to order this array depending on the code value but not in alphabetical order. (I specified this in bold but got eventually flagged anyway, people don't even care about reading the question)

For example I would like to have all the green objects, then all the blue ones and then all the red ones. What is the best way to do that?

[
    { code: "RED", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0}
]

Is it possible to do that with the sort function? What would the condition be in that case?

You could take an object for the wanted order.

var array = [{ code: "RED", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }, { code: "RED", value: 0 }, { code: "GREEN", value: 0 }, { code: "BLUE", value: 0 }],
    order = { GREEN: 1, BLUE: 2, RED: 3 };
    
array.sort(function (a, b) {
    return order[a.code] - order[b.code];
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sorting an array of objects, The employees array above is an array of objects with properties of different data to sort an array containing primitive values (such as strings) alphabetically, to sort using is deep inside a property of the array object, and not the array itself. When we return 1, the function communicates to sort() that the object b takes precedence in sorting over the object a.Returning -1 would do the opposite.. The callback function could calculate other properties too, to handle the case where the color is the same, and order by a secondary property as well:

Set the custom priority first

var codePriority = [ "GREEN", "BLUE", "RED" ];

Now use the same in sorting as

arr.sort( function(a,b){ 
   if ( a.code == b.code ) return a.value - b.value;
   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) ; notice this line
})

Demo

var arr = [
    { code: "RED", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0},
    { code: "RED", value: 0},
    { code: "GREEN", value: 0},
    { code: "BLUE", value: 0}
];
var codePriority = [ "GREEN", "BLUE", "RED" ];
arr.sort( function(a,b){ 
   if ( a.code == b.code ) return a.value - b.value;
   return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code )
});
console.log( arr );

How to sort an array of objects in JavaScript, Arrays in JavaScript come with a built-in function that is used to sort elements in alphabetical order. However, this function does not directly work on arrays of numbers or objects. Instead a custom function, that can be passed to the built-in sort() method to sort objects console.log("Sorting based on the item property");. 33. A simple function that sort an array of object by a property. function sortArray(array, property, direction) { direction = direction || 1; array.sort(function compare(a, b) { let comparison = 0; if (a[property] > b[property]) { comparison = 1 * direction; } else if (a[property] < b[property]) { comparison = -1 * direction; } return comparison; }); return array; // Chainable }

You could implement a schema array and sort according to element's index inside that schema array.

const a = ['GREEN', 'BLUE', 'RED'];

const o = [{code:"RED",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0},{code:"RED",value:0},{code:"GREEN",value:0},{code:"BLUE",value:0}];

const r = o.slice().sort(({ code: q }, { code: w }) => a.indexOf(q) - a.indexOf(w));

console.log(r);

Quick Tip: How to Sort an Array of Objects in JavaScript, Using Array.sort alone wouldn't be very useful for sorting an array of to check if the specified property is defined on each object and has not� I have to create a method that sorts an ArrayList of objects alphabetically according to email and then prints the sorted array. The part that I am having trouble with it sorting it. I have researched it and tried using Collections.sort(vehiclearray); but that didn't work for me. I was that I needed something called a comparator but couldn't

I was dealing with a case where I had to match a string status and sort by the various statuses specifically. .findIndex and .includes ended up being the best approach.

statusPriority sets the intended order. Once the indexes are found they can be compared and returned to the .sort

let records = [
  {status: 'Record is ready to submit.', active: true, name: 'A'},
  {status: 'Record has been sent.', active: true, name: 'B'},
  {status: 'Activation is required.', active: true, name: 'C'},
  {status: 'Record submission failed.', active: true, name: 'D'},
  {status: 'Creation is pending.', active: true, name: 'E'},
]

console.log(records.map(r => r.status))

let statusPriority = ['creation', 'activation', 'sent', 'ready', 'failed'];
records.sort((a, b) => {
  let aIndex = statusPriority.findIndex(status => a.status.toLowerCase().includes(status));
  let bIndex = statusPriority.findIndex(status => b.status.toLowerCase().includes(status));
  return aIndex - bIndex;
})

console.log(records.map(r => r.status))

Array.prototype.sort(), The default sort order is ascending, built upon converting the elements If compareFunction is not supplied, all non- undefined array elements are sorted by Objects can be sorted, given the value of one of their properties. If you have an array of objects that you need to sort into a certain order, you might be tempted to reach for a JavaScript library. But before you do, remember that you can do some pretty neat

How to sort an array of custom JavaScript objects, Sorting a JavaScript array of strings or numbers is easy with the Array.sort() that we want to sort the array alphabetically based on the title of our custom objects. two objects are instances of our MyItem class, so we can access properties of� When comparing 40 and 100, the sort() method calls the compare function(40, 100). The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort function will sort 40 as a value lower than 100. You can use this code snippet to experiment with numerically and alphabetically sorting:

JavaScript Array sort: Sorting an Array More Effectively, This tutorial shows you how to use the JavaScript array sort method to sort arrays of numbers, arrays of strings, and arrays of objects by a property. To sort this array alphabetically, you need to use a custom compare function to convert all with non-ASCII characters e.g., �, �, etc., the sort() method will not work correctly. You can sort different properties in different orders by using hash tables in an array. Each hash table uses an Expression key to specify the property name as string and an Ascending or Descending key to specify the sort order by $true or $false. The Expression key is mandatory. The Ascending or Descending key is optional.

Python: How to Sort a List? (The Right Way), In Python, you can sort a list of number, strings, tuples, or any other object. any object. I will also teach you how to define your own custom sort functions. Read the whole article if you want to learn all about list sorting in Python. Now let's say you want to sort the objects in this list alphabetically by the name attribute.

Comments
  • @JasperSeinhorst I just looped through the array, I wanted to see if there was a faster way.
  • @lilezek please read the question before flagging, I DON'T WANT IT TO BE ALPHABETICALLY ORDERED
  • @LucaDeNardi You just have to write your own sorting function, literally.
  • @lilezek not true at all, since someone provided a faster way to do that.
  • @LucaDeNardi everyone here provided a sorting function.
  • Mmm this is interesting! I didn't think about using an object to keep track of the order :)
  • You can remove the if check. Try return codePriority.indexOf( a.code ) - codePriority.indexOf( b.code ) || a.value - b.value
  • @Rajesh ohh, didn't thought of that :)... I would keep this as is for now, its more readable.