0

I have following 2D array: [["fox", "100"], ["the", "1"], ["quick", "50"]]

And want to store only the first element of the array, but sorted based on the second value.

Desired output: the,quick,fox

I have written a loop that iterates over the first elements which seems to work, however I cannot get it sorted based on the second value:

for (var i = 0; i < inputArr.length; i++) {
  x1 += inputArr[i][0];
  if(i != inputArr.length - 1){ 
   x1 = x1 + ",";
  }
 }

  
Write(x1); //outputs -> fox,the,quick
1
  • My naive attempt would be inputArr.sort((a,b) => a[1]-b[1]).map(([a]) => a).flat().join(',') - flat might be unneeded though... Commented Jun 8, 2021 at 9:32

1 Answer 1

2

You can use sort function of Array. The sort function takes a lambda function with 2 inputs based on return value decides the order

let arr = [["fox", "100"], ["the", "1"], ["quick", "50"]];

let output= arr.sort((a,b) => a[1]-b[1]).map(e => e[0]).join(",");

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

2 Comments

Whenever I saw "5" - "1" , it always shocks me. I always use Number() or + before doing maths with js number. please note: "5" + "1" = "51" but "5"-"1" = 4.
Note that sort manipulates the source array. Meaning arr will be sorted as well. This might or might not be desirable. If not, slice or concat are simple ways to make a copy before sorting.

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.