简体   繁体   中英

Sorting a JSON array with multiple objects and no keys

I have the following array, it has multiple objects but no keys.

const result = [
  ["Joe", "1", "2.22%", "$3,000.00"], 
  ["Tom", "1", "2.22%", "$4,650.00"], 
  ["Ryan", "4", "4.44%", "$18,925.00"], 
  ["Jordan", "2", "4.44%", "$3,300.00"], 
  ["Fred", "0", "0.00%", "$0.00"], 
  ["Steve", "0", "0.00%", "$0.00"]
]

I'm trying to sort by the 4th object but I'm have a really tough time figuring this out. Is there a quick an easy way to get this done without altering the array?

I'd like to return the results sorted where the 4th object is in desc order.

return {result: result[0][0] + ": " + result[0][3] + '\n' + result[1][0] + ': ' + result[1][3] + '\n' + result[2][0] + ': ' + result[2][3] + '\n' + result[3][0] + ': ' + result[3][3] + '\n' + result[4][0] + ': ' + result[4][3] + '\n' + result[5][0] + ': ' + result[5][3] };

So that the returned results look like:

Ryan: $18,925.00

Tom: $4,650.00

Jordan: $3,300.00

Joe: $3,000.00

Fred:$0.00

Steve: $0.00

You could get a normalized value without unwanted characters as number and return the delta for sorting.

 const normalize = s => s.replace(/[^\\d.]/g, ''); var array = [["Joe", "1", "2.22%", "$3,000.00"], ["Tom", "1", "2.22%", "$4,650.00"], ["Ryan", "4", "4.44%", "$18,925.00"], ["Jordan", "2", "4.44%", "$3,300.00"], ["Fred", "0", "0.00%", "$0.00"], ["Test", "0", "0.00%", "$0.00"]], result = array .sort((a, b) => normalize(b[3]) - normalize(a[3])) .map(({ [0]: name, [3]: amount }) => [name, amount]); console.log(result);

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