Sort by two values prioritizing on one of them

2019-01-02 20:59发布

How would I sort this data by count and year values in ascending order prioritizing on the count value?

//sort this
var data = [
    { count: '12', year: '1956' },
    { count: '1', year: '1971' },
    { count: '33', year: '1989' },
    { count: '33', year: '1988' }
];
//to get this
var data = [
    { count: '1', year: '1971' },
    { count: '12', year: '1956' },
    { count: '33', year: '1988' },
    { count: '33', year: '1989' },
];

7条回答
若你有天会懂
2楼-- · 2019-01-02 21:15

user this where 'count'-> first priority and 'year'-> second priority

data.sort(function(a,b){
  return a['count']<b['count']?-1:(a['count']>b['count']?1:(a['year']<b['year']?-1:1));
});
查看更多
无色无味的生活
3楼-- · 2019-01-02 21:22

Based on great @RobG solution, this is a generic function to sort by multiple different properties, using a JS2015 tricky on map + find:

let sortBy = (p, a) => a.sort((i, j) => p.map(v => i[v] - j[v]).find(r => r))

sortBy(['count', 'year'], data)

Also, if you prefer, a traditional JS version (use with caution due to find compatibility in old browsers):

var sortBy = function (properties, targetArray) {
  targetArray.sort(function (i, j) {
    return properties.map(function (prop) {
      return i[prop] - j[prop];
    }).find(function (result) {
      return result;
    });
  });
};
查看更多
残风、尘缘若梦
4楼-- · 2019-01-02 21:23

You can use JavaScript's .sort() array method (try it out):

data.sort(function(a, b) {
    // Sort by count
    var dCount = a.count - b.count;
    if(dCount) return dCount;

    // If there is a tie, sort by year
    var dYear = a.year - b.year;
    return dYear;
});

Note: This changes the original array. If you need to make a copy first, you can do so:

var dataCopy = data.slice(0);
查看更多
几人难应
5楼-- · 2019-01-02 21:28

If you are looking to sort strings in alphabetical order rather than numbers, here's a sample problem and its solution.

Example Problem: Array of arrays (finalArray) with first entry a folder path and second entry the file name; sort so that array is arranged by folder first, and within identical folders, by file name.

E.g. after sorting you expect:

[['folder1', 'abc.jpg'], 
 ['folder1', 'xyz.jpg'],
 ['folder2', 'def.jpg'],
 ['folder2', 'pqr.jpg']]

Refer to Array.prototype.sort() - compareFunction

finalArray.sort((x: any, y: any): number => {
  const folder1: string = x[0].toLowerCase();
  const folder2: string = y[0].toLowerCase();
  const file1: string = x[1].toLowerCase();
  const file2: string = y[1].toLowerCase();

  if (folder1 > folder2) {
    return 1;
  } else if (folder1 === folder2 && file1 > file2) {
    return 1;
  } else if (folder1 === folder2 && file1 === file2) {
    return 0;
  } else if (folder1 === folder2 && file1 < file2) {
    return -1;
  } else if (folder1 < folder2) {
    return -1;
  }
});

Keep in mind, "Z" comes before "a" (capitals first according to Unicode code point) which is why I have toLowerCase(). The problem the above implementation does not solve is that "10abc" will come before "9abc".

查看更多
后来的你喜欢了谁
6楼-- · 2019-01-02 21:31

you have to work out this problem like this way

var customSort = function(name, type){
     return function(o, p){
         var a, b;
         if(o && p && typeof o === 'object' && typeof p === 'object'){
            a = o[name];
            b = p[name];
           if(a === b){
              return typeof type === 'function' ? type(o, p) : o;
           }

           if(typeof a=== typeof b){
              return a < b ? -1 : 1;
            }
          return typeof a < typeof b ? -1 : 1;
        }
     };

};

e.g : data.sort(customSort('year', customSort('count')));

查看更多
素衣白纱
7楼-- · 2019-01-02 21:38

(See the jsfiddle)

data.sort(function (x, y) {
    var n = x.count - y.count;
    if (n !== 0) {
        return n;
    }

    return x.year - y.year;
});
查看更多
登录 后发表回答