Reputation: 2060
I am looping through an object and then upon each object I am comparing it to the items in my array in hopes to then push the objects that are not the same into my ItemsNotInObject array. Hopefully someone can shine some light on this for me. Thank you in advance.
var obj = {a:1, a:2, a:3};
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = [];
for (var prop in obj) {
for(var i = 0, al = array.length; i < al; i++){
if( obj[prop].a !== array[i] ){
ItemsNotInObject.push(array[i]);
}
}
}
console.log(ItemsNotInObject);
//output of array: 1 , 4 , 2 , 5, 6
//output desired is: 4 , 5 , 6
Upvotes: 0
Views: 72
Reputation: 30557
JSON
object. Make them uniqueobj[prop].a
, obj[prop]
is a
indexOf()
to check if the array contains the object property or not.var obj = {
a: 1,
b: 2,
c: 3
};
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = array.slice(); //clone the array
for (var prop in obj) {
if (array.indexOf(obj[prop]) != -1) {
for (var i = 0; i < ItemsNotInObject.length; i++) {
if (ItemsNotInObject[i] == obj[prop]) {
ItemsNotInObject.splice(i, 1); //now simply remove it because it exists
}
}
}
}
console.log(ItemsNotInObject);
Upvotes: 1
Reputation: 51
If you can make your obj variable an array, you can do it this way;
var obj = [1, 2, 3];
var array = [1, 4, 2, 5, 6];
var ItemsNotInObject = [];
for(i in array){
if( obj.indexOf(array[i]) < 0) ItemsNotInObject.push(array[i]);
}
console.log(ItemsNotInObject);
if the obj variable needs to be json object please provide the proper form of it so i can change the code according to that.
Upvotes: 1