Sort Multidimensional Array java script

Asked

Viewed 80 times

-1

I have the following array:

inserir a descrição da imagem aqui

I’d like to order the same for

id - 15135
id - 50
id - 25

I tried to use

 array.sort 

but it didn’t work.

  • 1

    Can you put the console text here, as text and not image, ? so it makes life easier for those who want to help with an example.

  • sort is a method so it would have to be array.sort() but without seeing how the code is hard to help

1 answer

1


var meuArray = [['4togm90gjwegn', 50], ['ef84itjdpodsdf4jg', 25], ['32r8uoijgtsdfsht', 15135]];

//Para ordenar em ordem crescente
meuArray.sort((a, b) => a[1] - b[1]);
//Para ordenar em ordem decrescente
meuArray.sort((a, b) => b[1] - a[1]);

The Sort method, if called without any parameter attempts to sort its array by comparing string values, but when its array is not made up of strings, you can pass a callback function with instructions for the organization.

This function takes 2 arguments, the first and the next item of the array (a and b), so it is up to you to return a number greater than 0 to say that the element a precedes b, or less than 0 to say that b precedes a. Since the values compared are numerical, in which case you can just subtract them.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.