1

Is there an optimal way to compare a property value from two array of objects using lodash/underscorejs?

I have an array like this.

var a = [{'text':1}, {'text':2, 'misc':22}, {'text':3}];
var b = [{'text':1}, {'text':2}, {'text':3}];

comparing a and b should return true based on the property 'text'.

Have tried using _.isEqual and _.isMatch with not much help.

Here is the JSFIDDLE

2 Answers 2

4

You can use pluck _.pluck( list, key) to get the values of key in a list of objects in list, so get the values of text and compare

_.isEqual(_.pluck(a, "text"),_.pluck(b, "text"));

http://jsfiddle.net/mhqpe06h/1/

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

1 Comment

Thank you, it was quick and easy. Accepting this as answer, as I was looking for underscorejs based.
1

This is pretty easy without any library, although libraries provide alternative implementations for Array#every:

var same = a.length === b.length && a.every(function(value, index) {
    return value.text === b[index].text;
});

2 Comments

This assumes that both arrays are sorted
Of course, I assume the array is used as a list, so the order is important. For me [a, b] is certainly different from [b, a]. If that's not what the OP wants, they should clarify their question.

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.