-3

I have two JavaScript arrays (say newvalue and oldvalue).

These two arrays contain some common values. I want to delete all the values present in oldvalue from the array newvalue.

Example:say newvalue has values 1,2,3,4 and oldvalue has values 2,3 I want to delete 2,3 from newvalue and newvalue should have values 1,4

This has to be done in JavaScript.

consider this as new value

[
{"patentid":1,
"Geography":"china",
"type":"utility",
"Assignee":"abc"
},
{"patentid":2,
"Geography":"aus",
"type":"utility",
"Assignee":"abc"
},
{"patentid":3,
"Geography":"aus",
"type":"utility",
"Assignee":"abc"
},
{"patentid":4,
"Geography":"china",
"type":"utility",
"Assignee":"xyz"
}
]


consider this as old value


[{"patentid":3,
"Geography":"aus",
"type":"utility",
"Assignee":"abc"
},
{"patentid":4,
"Geography":"china",
"type":"utility",
"Assignee":"xyz"
}]

Now I have to remove objects with patent id 3 and 4 in newvalue

Nithin A
  • 374
  • 1
  • 2
  • 18

2 Answers2

1

If it actually is common objects (that is, o1 === o2 is true), then you can do something like this:

var o1 = { id: 1 };
var o2 = { id: 2 };
var o3 = { id: 3 };
var o4 = { id: 4 };

var newvalue = [o1, o2, o3, o4];
var oldvalue = [o2, o3];

newvalue = newvalue.filter(function(e) { return oldvalue.indexOf(e) === -1 });
folkol
  • 4,752
  • 22
  • 25
  • If they are just 'similar' objects, you will have to define when they 'are the same', and use your own 'indexOf' (or 'contains') to use in your filter. – folkol Jun 26 '15 at 14:19
1

You can resolve it using Array.filter and Array.indexOf functions. Your example could be resolved like this:

[1,2,3,4].filter(function(e){ 
  return [2,3].indexOf(e) === -1;
});

You can too, use a library like lodash which has a lot of functions to solve these kinds of array manipulation.

borja gómez
  • 1,001
  • 8
  • 19
  • [1,2,3,4].filter(function(e){ return [2,3].indexOf(e) === -1}); – borja gómez Jun 26 '15 at 13:04
  • Yes i'm new to stackoverflow now i think i've done it better thanks – borja gómez Jun 26 '15 at 13:10
  • 1
    @NithinQ So now that he's correctly answered the original question, he's now supposed to provide another solution for the new version of your question? How many more times do you plan on changing your question? In any case, the principle provided in this answer will work for your revised question. Why don't you accept it and move on. –  Jun 26 '15 at 13:47