Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if an array is a subset of another array (but checking against a property)

I know this works (returns true)

var arr1 = [1, 'a', 2, 'b', 3];
var arr2 = [1, 2, 3];

var isSuperset = arr2.every(function (val) { return arr1.indexOf(val) >= 0; });

However say array1 consists of objects, and I want to check array2 against a certain property of the object:

var object1 = {name:'one'}
var object2 = {name:'two'}
var object3 = {name:'three'}

var arr1 = [object1,object2,object3];
var arr2 = ['one','two'];
var isSuperset = arr2.every(function (val) { return arr1.indexOf(val) >= 0; });

How can I ensure the every function checks against the name property?

like image 661
AlwaysNeedingHelp Avatar asked Mar 19 '23 01:03

AlwaysNeedingHelp


1 Answers

var object1 = {name: 'one'};
var object2 = {name: 'two'};
var object3 = {name: 'three'};

var arr1 = [object1,object2,object3];
var arr2 = ['one','two'];

// solution
var names = arr1.map(function(obj) { 
  return obj.name; 
});

var isSuperset = arr2.every(function(val) { 
  return names.indexOf(val) >= 0;
});

alert(isSuperset);
like image 52
sjkm Avatar answered Mar 26 '23 03:03

sjkm