Suppose we have an object like this −
const obj = { key1: 56, key2: 67, key3: 23, key4: 11, key5: 88 };
We are required to write a JavaScript function that takes in this object and returns a sorted array like this −
const arr = [11, 23, 56, 67, 88];
Here, we sorted the object values and placed them in an array.
Example
Following is the code −
const obj = { key1: 56, key2: 67, key3: 23, key4: 11, key5: 88 }; const sortObject = obj => { const arr = Object.keys(obj).map(el => { return obj[el]; }); arr.sort((a, b) => { return a - b; }); return arr; }; console.log(sortObject(obj));
Output
This will produce the following output in console −
[ 11, 23, 56, 67, 88 ]