admin管理员组文章数量:1134248
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}
];
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}
];
Share
Improve this question
edited Feb 21, 2014 at 9:11
Felix Kling
816k180 gold badges1.1k silver badges1.2k bronze badges
asked Nov 17, 2011 at 22:10
JohnJohn
13.7k14 gold badges109 silver badges189 bronze badges
13
- 1 What do you have so far? Why do you explicitly want a non-anonymous function? – pimvdb Commented Nov 17, 2011 at 22:12
- A non-anonymous function sorting(json_object,key_to_sort_by) {} – John Commented Nov 17, 2011 at 22:14
- Added the quotes, haven't coded for a few days! Just want to figure out how JSON and JavaScript set the key and then sort. Figure if it's not integer based I could use the sort method perhaps? – John Commented Nov 17, 2011 at 22:16
- Anonymous function example: window.onload = function() {/* stuff();*/} – John Commented Nov 17, 2011 at 22:16
- 5 What you list above is not JSON, it is a plain JavaScript object. JSON is the string encoded version of a JavaScript object. – Matt Commented Nov 17, 2011 at 22:17
13 Answers
Reset to default 144How about this?
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?
And here is a jsFiddle: http://jsfiddle.net/6Dgbu/
You can sort an array ([...]
) with the .sort
function:
var people = [
{'name': 'a75', 'item1': false, 'item2': false},
{'name': 'z32', 'item1': true, 'item2': false},
{'name': 'e77', 'item1': false, 'item2': false},
];
var sorted = people.sort(function IHaveAName(a, b) { // non-anonymous as you ordered...
return b.name < a.name ? 1 // if b should come earlier, push a to end
: b.name > a.name ? -1 // if b should come later, push a to begin
: 0; // a and b are equal
});
This isn't a JSON question, per se. Its a javascript array question.
Try this:
people.sort(function(a,b){
var x = a.name < b.name? -1:1;
return x;
});
I modified @Geuis 's answer by using lambda and convert it upper case first:
people.sort((a, b) => a.toLocaleUpperCase() < b.toLocaleUpperCase() ? -1 : 1);
My solution for similar sort problem using ECMA 6
var library = [
{name: 'Steve', course:'WAP', courseID: 'cs452'},
{name: 'Rakesh', course:'WAA', courseID: 'cs545'},
{name: 'Asad', course:'SWE', courseID: 'cs542'},
];
const sorted_by_name = library.sort( (a,b) => a.name > b.name );
for(let k in sorted_by_name){
console.log(sorted_by_name[k]);
}
Array.prototype.sort_by = function(key_func, reverse=false){
return this.sort( (a, b) => ( key_func(b) - key_func(a) ) * (reverse ? 1 : -1) )
}
Then for example if we have
var arr = [ {id: 0, balls: {red: 8, blue: 10}},
{id: 2, balls: {red: 6 , blue: 11}},
{id: 1, balls: {red: 4 , blue: 15}} ]
arr.sort_by(el => el.id, reverse=true)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},
{ id: 1, balls: {red: 4 , blue: 15 }},
{ id: 0, balls: {red: 8 , blue: 10 }} ]
*/
or
arr.sort_by(el => el.balls.red + el.balls.blue)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }}, // red + blue= 17
{ id: 0, balls: {red: 8 , blue: 10 }}, // red + blue= 18
{ id: 1, balls: {red: 4 , blue: 15 }} ] // red + blue= 19
*/
var data = [ 1, 2, 5, 3, 1];
data.sort(function(a,b) { return a-b });
With a small compartor and using sort, we can do it
Sorting alphabetically with lambda function:
arr.sort((a, b) => a.name.localeCompare(b.name));
This is how simply I sort from previous examples:
if my array is items
:
0: {id: 14, auctionID: 76, userID: 1, amount: 39}
1: {id: 1086, auctionID: 76, userID: 1, amount: 55}
2: {id: 1087, auctionID: 76, userID: 1, amount: 55}
I thought simply calling items.sort()
would sort it it, but there was two problems:
1. Was sorting them strings
2. Was sorting them first key
This is how I modified the sort function:
for(amount in items){
if(item.hasOwnProperty(amount)){
i.sort((a, b) => a.amount - b.amount);
}
}
In case if the array is:
[
{price:"10"},
{price:"110"},
{price:"22"},
]
then : (editing John's solution)
export const sortArrByKey = (array: any[], key: string) => {
return array.sort(function (a, b) {
var x = Number(+a[key]) || a[key];
var y = Number(+b[key]) || b[key];
return x < y ? -1 : x > y ? 1 : 0;
});
};
var library = [
{name: 'Steve', course:'WAP', courseID: 'cs452'},
{name: 'Rakesh', course:'WAA', courseID: 'cs545'},
{name: 'Asad', course:'SWE', courseID: 'cs542'},
];
const sorted_by_name = library.sort( (a,b) => a.name > b.name );
for(let k in sorted_by_name){
console.log(sorted_by_name[k]);
}
var library = [
{name: 'Steve', course:'WAP', courseID: 'cs452'},
{name: 'Rakesh', course:'WAA', courseID: 'cs545'},
{name: 'Asad', course:'SWE', courseID: 'cs542'},
];
const sorted_by_name = library.sort( (a,b) => a.name > b.name ? 1:-1 );
for(let k in sorted_by_name){
console.log(sorted_by_name[k]);
}
var people =
[{"name": 'a75',"item1": "false","item2":"false"},
{"name": 'z32',"item1": "true","item2": "false"},
{"name": 'e77',"item1": "false","item2": "false"}];
function mycomparator(a,b) { return parseInt(a.name) - parseInt(b.name); }
people.sort(mycomparator);
something along the lines of this maybe (or as we used to say, this should work).
本文标签: javascriptSimple function to sort an array of objectsStack Overflow
版权声明:本文标题:javascript - Simple function to sort an array of objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736848288a1955394.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论