0

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

1
  • i don't understand very well what result do you want to obtain? can you add it? Commented Jan 11, 2020 at 21:51

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

This is great but I'd like to return the currency characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.