0

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
1
  • Property names must be different. {a:1, a:2, a:3} becomes {a:3}. Commented Jun 24, 2015 at 23:18

2 Answers 2

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

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

1 Comment

This was such a simple fix, I thank you very much, king gentleman. I did indeed mess up the writing of my json, it's really in this form obj = [{key:value},{key:value}, {etc}]; But, nevertheless, slice saved my life. Thank you again.
1

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.

1 Comment

Thanks for the help, but turning into an array is not an option inside my application.

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.