0

I want to use lodash to convert an object like this:

var a = {1:'a', 3:'b', 2:'c'};

into a sorted array of values based on the keys of the object like:

var result = ['a','c','b'];

I know I can do this:

var keyRef = Object.keys(a).sort();
var result = keyRef.map(v => a[v]);

But is this way optimized - is there any function in lodash which is more optimized for this??

3 Answers 3

4

With plain Javascript, you could use Object.values and take this array as sorted result, because if the keys of the object could be read as 32 bit integer numbers, Javascript use them in numerical order.

Source:

var object = { 1: 'a', 3: 'b', 2: 'c' },
    values = Object.values(object);
    
console.log(values);

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

Comments

0

Using lodash,

const o = {1:'a', 3:'b', 2:'c'};
const res = _.sortBy(o, (a, b) => b);

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.core.js"></script>

Comments

0

Lodash has the _.values(obj) function. However it is noted that the result ordering is not guaranteed. However, as @Nina pointed out, if you stick to ints as the keys, the ordering should be consistent (unless lodash is doing something weird).

Comments

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.