Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a associative array into a sorted string array?

How can I convert this js object

 var obj1 =  {"user1":28, "user2":87, "user3":56};

into a string array, sorted by value, like so:

["user2","user3","user1"]
like image 850
Spike Flail Avatar asked May 25 '15 14:05

Spike Flail


People also ask

How do you convert associative array to string?

To convert an array to a string, one of the common ways to do that is to use the json_encode() function which is used to returns the JSON representation of a value. This function takes any value as input except resource.

How do you sort an associative array?

The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key.

What is the difference between associative array and array?

The index data type for a simple array must be an integer value. The index type for an associative array can be one of a set of supported data types. The index values in a simple array must be a contiguous set of integer values. In an associative array the index values can be sparse.

How do you unset an associative array in PHP?

Method 1: Using unset() function: The unset() function is used to unset a key and its value in an associative array. print_r( $arr ); ?> Method 2: Using array_diff_key() function: This function is used to get the difference between one or more arrays.


1 Answers

Use this:

var obj1 =  {"user1":28, "user2":87, "user3":56};
var a = Object.keys(obj1).sort(function(x,y){return obj1[y]-obj1[x]})
console.log(a);

Output:

["user2", "user3", "user1"]
like image 63
n-dru Avatar answered Oct 20 '22 00:10

n-dru