Sorting an array of objects

An object type is a collection of key-value pairs — properties in JavaScrip. KEY can be a string or a symbol, and VALUE can be any type (str, int, obj, arr), or even functions. There is no order for the object properties.

Bạn đang xem: Sorting an array of objects

obj = {'someKey': someValue,'anotherKey': anotherValue}What if you have an object and you need to sort properties by keys or values?

For example, you have this problem,

You have a grossaryList object, where the ‘key’ is the name of food and ‘value’ is the count. You need to return two keys with the greatest value from an object.

Example:

Input: grossaryList = { 'bread': 1, 'apple': 6, 'milk': 1, 'orange': 3, 'broccoli': 2 }//apple and orange are with the most count (6 and 3)Output: <'apple', 'orange'>How can I accomplish this, if I cannot sort object properties, since there is no order there, remember?

There are 3 useful methods to get ‘keys’ or ‘values’ or ‘key: value’ data from an object. I will use Object.entries, because I need both key: value for my task.

Object.keys(grossaryList) => <‘bread’, ‘apple’, ‘milk’, ’orange’, ’broccoli’>Object.values(grossaryList) => <‘1’, ‘6’, ‘1’, ’3’, ’2’>Object.entries(grossaryList) => <<'bread', 1>,<'apple', 6>,<'milk', 1>,<'orange', 3>,<'broccoli', 2>>

According to MDN Documentation: “The Object.entries() method returns an array of a given object's own enumerable string-keyed property pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well).”

grossaryList = { 'bread': 1, 'apple': 6, 'milk': 1, 'orange': 3, 'broccoli': 2 } return Object.entries(grossaryList) //=> <<'bread',1>,<'apple', 6>,<'milk', 1>,<'orange', 3>,<'broccoli', 2>>

*

*

Testing Object.entries() methodThe order of the array returned by Object.entries() does not depend on how an object is defined.

For certain ordering, you need to sort the array first. We can use the sort() method which in our case should look as follows:

grossaryList = { 'bread': 1, 'apple': 6, 'milk': 1, 'orange': 3, 'broccoli': 2 }return Object.entries(grossaryList).sort((a,b) => b<1>-a<1>)//=> <<'apple', 6>,<'orange', 3>,<'broccoli', 2>,<'bread',1>,<'milk', 1>>

*

*

Testing sort() method on Object.entries() method.As you can see we got an array of arrays sorted by values as the result.

Xem thêm: Php Designer 7 Free Download For Windows 10, 7, 8/8, Phpdesigner 8

Object.entries(grossaryList).sort((a,b) => b<1>-a<1>),where a meens current element and b meens next element in array.Because we have array of arrays <> we need another brackets b<1> to compare by second element in inner array which meens compare by values.As we are interested just in the keys from a sorted array, as the next step I am going to use array’s method map() to achieve that.

function sortObjectEntries(obj){return Object.entries(obj).sort((a,b)=>b<1>-a<1>).map(el=>el<0>)}