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"]
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.
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.
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.
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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With