Search code examples
javascriptarraysobjectfor-loopfor-in-loop

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


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

Solution

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