简体   繁体   English

如何按对象值对对象数组进行排序?

[英]How can I sort an array of objects by the object value?

I've this array of objects here in JS:我在 JS 中有这个对象数组:

const testObject = [
    {
        name: "Grinsendes Gesicht",
        icon: "😃",
        used: 3,
    },
    {
        name: "Hundegesicht",
        icon: "🐶",
        used: 8
    },
];

I'm looking now for an option to sort my array of objects descending by the used counter in each object so that it looks like this after sorting it:我现在正在寻找一个选项来按每个对象中使用的计数器降序对我的对象数组进行排序,以便在排序后看起来像这样:

const testObject = [
    {
        name: "Hundegesicht",
        icon: "🐶",
        used: 8
    },
    {
        name: "Grinsendes Gesicht",
        icon: "😃",
        used: 3,
    }
];

I've tried this but it's not working as expected:我试过这个,但它没有按预期工作:

 const testObject = [ { name: "Grinsendes Gesicht", icon: "😃", used: 3, }, { name: "Hundegesicht", icon: "🐶", used: 8 }, ]; console.log( testObject ); testObject.sort( function ( a, b ) { return a.used - b.used; } ); console.log( testObject );

For descending, you go the opposite对于下降,你走相反的方向

 const testObject = [ { name: "Grinsendes Gesicht", icon: "😃", used: 3, }, { name: "Hundegesicht", icon: "🐶", used: 8 }, ]; console.log( testObject ); testObject.sort( function ( a, b ) { return b.used - a.used; } ); console.log("Descending array:") console.log( testObject );

You are on the right track!你在正确的轨道上! The sort method is what you want to use, the issue you are running into is the return value. sort 方法是您要使用的方法,您遇到的问题是返回值。

Essentially what you should be returning is:基本上你应该返回的是:

  • a number below 0 (negative) if A should come before B如果 A 应该在 B 之前,则为小于 0(负)的数字
  • a number above 0 (positive) if B should come before A如果 B 应该在 A 之前出现一个大于 0(正)的数字
  • 0 if A and B are equal or incompatible 0 如果 A 和 B 相等或不兼容

You can read into this more here .您可以在此处阅读更多内容。

If you are trying to sort this descending, you want to do the reverse of what you currently have in your return statement:如果您尝试按降序排序,则需要对 return 语句中的当前内容进行相反的操作:

testObject.sort( function ( a, b ) { return b.used - a.used } );

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

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