-1

This is what I am trying.

var object1 = {name: 'one', psno:'34'};
var object2 = {name: 'two', psno:'34'};
var object3 = {name: 'three', psno:'345'};
var arr1 = [object1,object2,object3];
var arr2 = [object1,object2];
// solution
var names = arr1.map(function(obj) { 
  return obj.name; 
});
var isSuperset = arr2.every(function(val) { 
  return names.indexOf(val) >= 0;
});
alert(isSuperset);

It returns false instead of true. Where I am going wrong.

2

2 Answers 2

1

Thats because you're not doing .name when checking .indexOf

var object1 = {
  name: 'one',
  psno: '34'
};
var object2 = {
  name: 'two',
  psno: '34'
};
var object3 = {
  name: 'three',
  psno: '345'
};
var arr1 = [object1, object2, object3];
var arr2 = [object1, object2];
// solution
var names = arr1.map(function(obj) {
  return obj.name;
});
var isSuperset = arr2.every(function(val) {
//Ive changed this line!
  return names.indexOf(val.name) >= 0;
});
alert(isSuperset);

JS Fiddle here: https://jsfiddle.net/waqmafsa/

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

2 Comments

@Andy Thats because OP's code originally constructs an array of names alone and then proceeded to check if one was a superset of another! You should ideally check for properties which are unique aka id's. psno seems to be such an element. I dont see why you'd need to check both the id AND name when checking for the id will suffice(if psno is unique, that is. Im assuming this though OP's object1 and object2 both have the same psno). Aside from this, I do not see OP asking to check for psno anywhere in his question. There was a mistake in his code, and I simply corrected it.
Thanks Andy and Shashanka, Both the answers work perfectly but this one seems easy for me.
1

Here's a method that checks that all key/values in the objects match.

// creates a hash for each object
// e.g. "name|one|psno|34"
function hash(obj) {
  return Object.keys(obj).reduce(function(p, c) {
    return p.concat([c, obj[c]].join('|'));
  }, []).sort().join('|');
}

// returns a hashed object
function hashObject(obj) {
  return hash(obj);
}

// returns a function that checks to see
// if an element is in the array
function within(arr) {
  return function (el) {
    return arr.indexOf(el) > -1;
  }
}

// performs the check    
function check(arr1, arr2) {
  if (arr1.length < arr2.length) return false;
  var hashedArr1 = arr1.map(hashObject);
  return arr2.map(hashObject).every(within(hashedArr1));
}

var issubset = check(arr1, arr2);

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.