0

I have an jsonarray A but I would like to delete the elements which satisfy a certain condition. This condition is elements which have a certain id which are contained in another array called B. They both contain the same id property.

Suppose the arrays look like this:

A =[{"id":1},{"id":2},{"id":3}]
B =[{"id":1},{"id":2}]

So the function I am trying to create would result in:

result=[{"id":3}]

I tried this but not working:

result= _.each(A, function(gl) {
  return _.each(B, function(tg) {
    if (tg.id != gl.id) {
      return gl;
    }
  });
});

3 Answers 3

2

Try using reject to filter out values you don't want:

var A =[{"id":1},{"id":2},{"id":3}];
var B =[{"id":1},{"id":2}];
            
var result = _.reject(A, function(item) {
   return _.find(B, {id: item.id});
});

alert(JSON.stringify(result)); // [{"id":3}]
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.js"></script>

Some underscore methods you can use to check if A is in B are find, findIndex, and where.

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

Comments

1

where is also fine:)

var A = _.reject(A, function(item) {
   return _.where(B, {id: item.id}).length > 0
});

Comments

0

Easy using the open source project jinqJs

See Fiddle

var result = jinqJs().from(A).not().in(B, 'id').select();

1 Comment

jinqJs link brings to a survey.

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.