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

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

问题描述

我想创建一个(非匿名)函数,该函数按键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 sort_by_key(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 = sort_by_key(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天全站免登陆