-1

How to get different values from 2 object arrays using underscore js. I have 2 object arrays like this

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

My result should be like this

[{
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}]

Is there any inbuilt functions to this in underscorejs

4
  • What are you filtering from your array of as and bs to be within your result? Your result looks like it's just picking the last 3 items form array a. Commented Dec 5, 2017 at 13:46
  • @KristianRoebuck the result is non-common items from 2 object array Commented Dec 5, 2017 at 13:47
  • Please provide a proper explanation of the criteria for all to read. People shouldn't have to be diff tools to understand. Also show what you have tried that isn't working Commented Dec 5, 2017 at 13:48
  • In your example you have some objects in your results are exist within a and b. It's probably worth correcting that. Commented Dec 5, 2017 at 13:49

1 Answer 1

1

You could achieve it using _.reject and _.findWhere.

var a = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}, {
    "asset_id": 5,
    "asset_type": 2
}, {
    "asset_id": 9,
    "asset_type": 3
}, {
    "asset_id": 10,
    "asset_type": 3
}];

var b = [{
    "asset_id": 1,
    "asset_type": 2
}, {
    "asset_id": 1,
    "asset_type": 3
}, {
    "asset_id": 3,
    "asset_type": 3
}];

var newArr = _.reject(a, function(obj) {
  return _.findWhere(b, obj)
})

console.log(newArr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

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

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.