admin管理员组文章数量:1356751
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?
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?
Share Improve this question asked Oct 28, 2014 at 22:36 AlwaysNeedingHelpAlwaysNeedingHelp 1,9634 gold badges25 silver badges33 bronze badges 2-
3
var arr3 = arr1.map(function(val) { return val.name; })
and in the predicte ofarr2.every
, usereturn arr3.indexOf(val) >= 0;
. – The Paramagnetic Croissant Commented Oct 28, 2014 at 22:38 - Oh, you were faster, same solution, upvote – sjkm Commented Oct 28, 2014 at 22:41
1 Answer
Reset to default 8var 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);
本文标签:
版权声明:本文标题:javascript - Checking if an array is a subset of another array (but checking against a property) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744060532a2584050.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论