简体   繁体   中英

Sorting array of arrays on column

I have an array of arrays like this:

customers = [[439, "Customer A", 60800.0], [8, "Customer B", 264509.0], [546, "Customer C", 17900.0]]

How can I sort this on the 3rd column (the turnover), from high to low?

Use Enumerable#sort_by :

customers.sort_by { |e| -e[2] }
=> [[8, "Customer B", 264509.0],
    [439, "Customer A", 60800.0],
    [546, "Customer C", 17900.0]]

I would use Array#sort and use a block with it, which gets two elements they will be compared. I like these expressive notation.

Each of these elements is one of the inner arrays and I compare the third element (index is 2) of these arrays. y[2] <=> x[2] meens descending order and x[2] <=> y[2] meens ascending order. Note that all inner arrays need the third element. Otherwise you will get unexpected results.

customers.sort{|x,y| y[2] <=> x[2]}
# => [[8, "Customer B", 264509.0], [439, "Customer A", 60800.0], [546, "Customer C", 17900.0]]

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