简体   繁体   中英

How to sort array of objects according to a property of the object

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);
 }

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.

Assuming you're having integers like variables inside priorityTag s, 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)))

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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM