Get the App
SLTechnology News&Howtos  ›  Development  › 

How js sorts an array of objects by attributes

Shulou Source: shulou.com Published: 2022-06-01 04:58:44 09月15日 Update

This article mainly introduces js how to sort the array of objects by attributes, which is very detailed and has a certain reference value. Friends who are interested must read it!

Sort an array of objects by attribute

We know that the sort method in the JS array is sorted in dictionary order, so this method works well for string classes, but not for data elements that are object types, so we need to customize a sorting method here.

In the comparison function, we will return the value based on the following conditions:

Less than 0A before B

Greater than 0: B before A

Equal to 0: an and B remain the same to each other.

Const data = [{id: 1, name: 'Lemon', type:' fruit'}, {id: 2, name: 'Mint', type:' vegetable'}, {id: 3, name: 'Mango', type:' grain'}, {id: 4, name: 'Apple', type:' fruit'}, {id: 5, name: 'Lemon', type:' vegetable'}, {id: 6, name: 'Mint' Type: 'fruit'}, {id: 7, name:' Mango', type: 'fruit'}, {id: 8, name:' Apple', type: 'grain'},] function compare (a, b) {/ / Use toLowerCase () to ignore character casing const typeA = a.type.toLowerCase () Const typeB = b.type.toLowerCase (); let comparison = 0; if (typeA > typeB) {comparison = 1;} else if (typeA < typeB) {comparison =-1;} return comparison;} data.sort (compare) these are all the contents of the article "how to sort an array of objects by attributes". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Sorting objects arrays properties methods content articles values elements interests functions handy dictionaries characters strings boys buddies data more conditions Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno MariaDB Huawei Docker NVidia