1

I have the following:

a = {x:1, y:3, w:4}
b = {c:2, d:3}

And I want to obtain all the values of these objects iterating only once.

result = [1, 3, 4, 2, 3]

I have the following solution but it has multiple iterations.

result = _.chain(a).values().union(_.values(b)).value();

I would like to avoid the "_.values(b)" and do this using the same chain from a.

I also tried this, but it is not working properly:

result = _.chain({}).extend(a,b).values().value();
5
  • What you have is the best solution you can find I guess. Commented Mar 6, 2015 at 5:42
  • You could merge the objects, then get the values from the merged object. Commented Mar 6, 2015 at 5:52
  • 1
    @torazaburo That will not work if the objects have keys in common, right Commented Mar 6, 2015 at 6:02
  • @luis No, it won't, but you yourself showed a similar approach in your last code fragment (which works for me...why do you say "it is not working properly"?). Commented Mar 6, 2015 at 6:38
  • The problem comes when you have common keys between the 2 objects Commented Mar 6, 2015 at 19:05

2 Answers 2

1

If you're intent on chaining, then

_.chain([a, b])   .         // [ { x: 1, y: 3, w: 4 }, { c: 2, d: 3 } ]
    map(_.values) .         // [ [    1,    3,    4 ], [    2,    3 ] ]
    flatten()     .         // [      1,    3,    4,        2,    3   ]
    uniq()        .         // [      1,    3,    4,        2         ]
    value()
Sign up to request clarification or add additional context in comments.

Comments

0

How about.

var a = {x:1, y:3, w:4},
    b = {c:2, d:3};

result = _.values(_.extend(a,b));

4 Comments

Weird, I always get the same result. jsfiddle.net/jrmh35js Are you changing the input?
@GusOrtiz What if both the objects have same keys?
right that's the issue.. it's fine though, i can make my keys unique for my solution. thanks! is having _.chain({}).extend(a,b).values() any different than your solution? I thought the chain one was faster
Well I updated the fiddle adding the chain one, and timed them both. They usually end in the same time, but we´d need a lot of data to make a better benchmark. I don´t know the internals of underscore, so I wouldn't know which one is faster. jsfiddle.net/jrmh35js/1 Theres the updated fiddle.

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.