Looping through an object and a nested for loop that loops through array

82 views Asked by At

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
2

There are 2 answers

1
AmmarCSE On BEST ANSWER
  1. Your object has duplicate keys. This is not a valid JSON object. Make them unique
  2. Do not access the object value like obj[prop].a, obj[prop] is a
  3. Clone the original array.
  4. Use indexOf() to check if the array contains the object property or not.
  5. If it does, remove it from the cloned array.

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);

1
eaktas On

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.