简体   繁体   English

在嵌套键上排序数组

[英]Sort array on nested key

I am using this function to sort an array based on object key: 我正在使用此函数根据对象键对数组进行排序:

function keysrt(arr, key, reverse) {
    var sortOrder = 1;
    if(reverse){
        sortOrder = -1;
    }
    return arr.sort(function(a, b) {
        var x = a[key],
            y = b[key];

        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}   

It works well with this type of array, where key is on the first level: 它适用于这种类型的数组,其中键位于第一级:

var a = [ 
    { id: 0, last: 'Anne'},
    { id: 1, last: 'Odine'},
    { id: 2, last: 'Caroline'}
]

keysrt(a, 'last');

How can I make it work with this example, where title key is nested ? 如何使用此示例,其中title键是嵌套的

var b = [ 
    { id: 0, last: 'Anne',     data:{title: 'habc'}},
    { id: 1, last: 'Odine',    data:{title: 'asdf'}},
    { id: 2, last: 'Prentice', data:{title: 'tzuio'}}
]

keysrt(b, 'title');

For this idea the "key" variable changes into an array of keys: Then you specify the "path" to the nested value you want to sort on. 对于这个想法,“key”变量变为一个键数组:然后指定要排序的嵌套值的“路径”。

function keysrt(arr, keyArr, reverse) {
    var sortOrder = 1;
    if(reverse)sortOrder = -1;
    return arr.sort(function(a, b) {
        var x=a,y=b;
        for (var i=0; i < keyArr.length; i++) {
          x = x[keyArr[i]];
          y = y[keyArr[i]];
        }
        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
} 

keysrt(b,['data','title']);

If you are ready to change the function signature and the function call, here is a simple solution- 如果您准备更改功能签名和函数调用,这里有一个简单的解决方案 -

function keysrt(arr, prop, key, reverse) {
    var sortOrder = 1;
    if(reverse)sortOrder = -1;
    return arr.sort(function(a, b) {
        var x = a[prop][key]; var y = b[prop][key];
        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}   


var b = [ 
    { id: 0, last: 'Anne',     data:{title: 'habc'}},
    { id: 1, last: 'Odine',    data:{title: 'asdf'}},
    { id: 2, last: 'Prentice', data:{title: 'tzuio'}}
]

keysrt(b,'data', 'title');

Here, prop represents the outer object, key would represent the nested key. 这里, prop表示外部对象, key表示嵌套键。

So, var y = b[prop][key] would basically mean you are accessing b.data.title 所以, var y = b[prop][key]基本上意味着你正在访问b.data.title

Hope it helps :) Happy coding! 希望它有所帮助:)快乐的编码!

If you need to make it generic, I think you can pass in a function that will retrieve the value from array item for comparison: 如果你需要使它通用,我认为你可以传入一个函数,它将从数组项中检索值以进行比较:

function keysrt(arr, reverse, getValueFn) {
    var sortOrder = 1;
    if(reverse)sortOrder = -1;
    return arr.sort(function(a, b) {
        var x = getValueFn(a); var y = getValueFn(b);
        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

So that you can use it like: 所以你可以使用它:

keysrt(b, true, function(a){return a.data.title})   

To find a nested property value, any number of levels down, you can use JSON.stringify as a way to walk the object: 要查找嵌套属性值(任意数量的级别),可以使用JSON.stringify作为遍历对象的方式:

function get_nested_value(obj, prop) {
  var result;
  JSON.stringify(obj, function(key, value) {
    if (key === prop) result = value;
  });
  return result;
}

Now: 现在:

function keysrt(arr, key, reverse) {
    var sortOrder = 1;
    if(reverse){
        sortOrder = -1;
    }
    return arr.sort(function(a, b) {
        var x = get_nested_value(a, key);
            y = get_nested_value(b, key);

        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}  

You can get working example with following code: 您可以使用以下代码获得工作示例:

function keysrt(arr, key, reverse) {
    var sortOrder = reverse ? -1 : 1;

    return arr.sort(function(a, b) {
        var x,y;

        if(typeof a[key] !== "undefined") {
          x = a[key]; 
          y = b[key];
        } else {
          for(var prop in a) {
            if(a[prop][key] !== "undefined") {
              x = a[prop][key];
              y = b[prop][key];
            }
          }
        }

        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}   

but I would propose more generic solution 但我会提出更通用的解决方案

function keysrt(arr, path, reverse) {
    var sortOrder = reverse ? -1 : 1;
    var pathSplitted = path.split(".");

    if(arr.length <= 1) {
      return arr;
    }

    return arr.sort(function(a, b) {
        var x = a;
        var y = b;

        pathSplitted.forEach(function(key) {
          x = x[key];
          y = y[key];
        });     

        return sortOrder * ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}   

in which one can provide a path to sorting field like this 其中一个可以像这样提供排序字段的路径

var sorted = keysrt(b, 'data.title');

Demo: http://jsbin.com/cosugawoga/edit?js,console 演示: http//jsbin.com/cosugawoga/edit?js,console

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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