用于对对象数组进行排序的简单函数 [英] Simple function to sort an array of objects

查看:169
本文介绍了用于对对象数组进行排序的简单函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个(非匿名)函数,按键 name 按字母顺序对对象数组进行排序。我只编写直接JavaScript代码,所以框架至少对我没用。

I would like to create a (non-anonymous) function that sorts an array of objects alphabetically by the key name. I only code straight-out JavaScript so frameworks don't help me in the least.

var people = [
    {'name': 'a75', 'item1': false, 'item2': false},
    {'name': 'z32', 'item1': true,  'item2': false},
    {'name': 'e77', 'item1': false, 'item2': false}
];


推荐答案

这个怎么样?

var people = [
{
    name: 'a75',
    item1: false,
    item2: false
},
{
    name: 'z32',
    item1: true,
    item2: false
},
{
    name: 'e77',
    item1: false,
    item2: false
}];

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

people = sortByKey(people, 'name');

这允许您指定要对数组进行排序的键,以便您不受限制到硬编码的名称排序。它将对所有共享属性的对象数组进行排序,这些属性用作键。我相信你正在寻找的是什么?

This allows you to specify the key by which you want to sort the array so that you are not limited to a hard-coded name sort. It will work to sort any array of objects that all share the property which is used as they key. I believe that is what you were looking for?

这里有一个jsFiddle: http://jsfiddle.net/6Dgbu/

And here is a jsFiddle: http://jsfiddle.net/6Dgbu/

这篇关于用于对对象数组进行排序的简单函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆