0

I have an Array of objects. each object in the Array has a property called "priorityTag"

I would like to sort the Array ascendingly according the "priorityTag". So, I wrote the below posted code, but it does not work.

please let me know how to sort the Array according to the "priorityTag"

Note: priortyTag is a property in of the object that is contained in the Array. in other words, each element in the Array is an object, and each object has a alot of properties, but one of These properties is "PriorityTag"

I want to sort the Array according to the "priorityTag"

code:

sortFeaturesPerPriority2(arr) {
logger.debug('[sortFeaturesPerPriority2]: arr:', arr);

 arr.sort((a, b) => a.priorityTag - b.priorityTag);
 }
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • 3
    what is in priorityTag ? – Logar May 17 '18 at 14:29
  • https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript - I guess this is what you were looking for – sander May 17 '18 at 14:30
  • @Logar i edited my question – Amrmsmb May 17 '18 at 14:32
  • 1
    What you've got there should work provided the priority tag is a number – Andrew Bone May 17 '18 at 14:32
  • I meant, what is the type of the variable ? as @AndrewBone said, this code should work if you are working with numbers – Logar May 17 '18 at 14:33
  • Possible duplicate of [Sort array of objects by string property value in JavaScript](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Christian Benseler May 17 '18 at 14:41
  • I guess it would hav to return the sorted array at the minute I think it's just lost once the function is done. – Andrew Bone May 17 '18 at 14:43
  • @AndrewBone what do you mean ? Array.prototype.sort() is a synchronous function, mutating your array. So your array should be sorted if you look for it right after the function call – Logar May 17 '18 at 14:56
  • even though arr is a parameter sent in with the function sortFeaturesPerPriority2(arr)? I'm not 100% on how that works – Andrew Bone May 17 '18 at 14:58
  • 1
    In your case, yes it should still work, arrays are passed by reference. Just to make sure, Can you try to log your array right after `arr.sort(..` and right after the call of `sortFeaturesPerPriority2` ? – Logar May 17 '18 at 15:08

3 Answers3

0

To do that, you can use a prototype I've done

/**
 * ARRAY PROTOTYPE SORT BY
 * Used to sort an array by object field
 * @param {String} field
 */
Array.prototype.sortBy = function (field = '') {
    this.sort(function (a, b) {
        return a[field] == b[field] ? 0 : +( a[field] > b[field]) || -1;
    });
};

You can use like this :

let array = [{name: 'Jonh', age: 71}, {name: 'Tracey', age: 58}];
array.sortBy('age');
console.log(array); // Display [ { name: 'Tracey', age: 58 }, { name: 'Jonh', age: 71 } ]

Hope it helps.

Sparw
  • 2,688
  • 1
  • 15
  • 34
0

Assuming you're having integers like variables inside priorityTags, you need to parse them before sorting

sortFeaturesPerPriority2(arr) {
    logger.debug('[sortFeaturesPerPriority2]: arr:', arr);

     arr.sort(({priorityTag: p1}, {priorityTag: p2}) => parseInt(p1) - parseInt(p2));
 }

If you cannot parse your priorityTags into numeric values (let's say you have priorityTag == 'a' or priorityTag == 'b'), you can look at the link provided by @sander in the comments

Edit

Not really answering OP's question, but here is a neat way of defining all kinds of sorts by properties :

const arr = [
  {priorityTag: 'a'}, 
  {priorityTag: 'e'},
  {priorityTag: 'd'},
  {priorityTag: 'b'},
  {priorityTag: 'c'}, 
];

const numericSort = prop => ({[prop]: a}, {[prop]: b}) => a - b;
const alphaSort = prop => ({[prop]: a}, {[prop]: b}) => a < b ? -1 : 1;
const weirdCustomSort = prop => ({[prop]: a}, {[prop]: b}) => {
  const elements = ['a','e','b','d','c'];
  const aIndex = ~elements.indexOf(a) ? elements.indexOf(a) : elements.length;
  const bIndex = ~elements.indexOf(b) ? elements.indexOf(b) : elements.length;
  return aIndex - bIndex;
};

const compareBy = prop => sortFunc => sortFunc(prop)

console.log([...arr].sort(compareBy('priorityTag')(alphaSort)))
console.log([...arr].sort(compareBy('priorityTag')(numericSort)))
console.log([...arr].sort(compareBy('priorityTag')(weirdCustomSort)))
Logar
  • 1,248
  • 9
  • 17
0

Assuming priority tag is a number then this looks right. I tried with those code and it ordered them

const arr = [
  {priorityTag: 1},
  {priorityTag: 5},
  {priorityTag: 0},
  {priorityTag: 2},
  {priorityTag: 6},
]
arr.sort( (a,b) => a.priorityTag - b.priorityTag ); // 0,1,2,5,6

If the priorityTag is a string then I would just use the following. This actually will work for both strings and numbers assuming you're ok how the greater than works with strings by default.

arr.sort( (a,b) => a.priorityTag > b.priorityTag );
James Q Quick
  • 429
  • 3
  • 5
  • I believe the comparison function must return an integer, not sure what the behaviour will be with a boolean, but I remember I had troubles using a boolean return type – Logar May 17 '18 at 14:44
  • @logar hmm good point. I didn't realize that actually. I guess the boolean is just being casted to an integer implicitly? Seems to be working for this simple example at least, but I'll keep an eye out in the future. – James Q Quick May 17 '18 at 15:22