简体   繁体   中英

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

I've this array of objects here in 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.

Essentially what you should be returning is:

  • a number below 0 (negative) if A should come before B
  • a number above 0 (positive) if B should come before A
  • 0 if A and B are equal or incompatible

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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