admin管理员组

文章数量:1287920

I need to check if all items in an array can be found within another array. That is, I need to check if one array is a subset of another array.

Example:

var array = [1, 2, 5, 7];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

Comparing these two arrays above should return true as all items in array can be found in otherArray.

var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

Comparing these two arrays above should return false as one of the items in array cannot be found in otherArray.

I have tried to use the indexOf method inside a for loop without success. I hope someone could help me. :)

I need to check if all items in an array can be found within another array. That is, I need to check if one array is a subset of another array.

Example:

var array = [1, 2, 5, 7];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

Comparing these two arrays above should return true as all items in array can be found in otherArray.

var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

Comparing these two arrays above should return false as one of the items in array cannot be found in otherArray.

I have tried to use the indexOf method inside a for loop without success. I hope someone could help me. :)

Share Improve this question edited May 3, 2016 at 3:41 timolawl 5,56415 silver badges29 bronze badges asked May 2, 2016 at 19:01 regniscireregniscire 1175 bronze badges 2
  • 1 Do you know ahead of time if the arrays are always sorted? – Explosion Pills Commented May 2, 2016 at 19:06
  • If otherArray is large, it would be best to convert it to an object whose keys are the elements. – Barmar Commented May 2, 2016 at 19:38
Add a ment  | 

1 Answer 1

Reset to default 17

Use Array.prototype.every:

The every() method tests whether all elements in the array pass the test implemented by the provided function.

var array = [1, 2, 7, 9];
var otherArray = [1, 2, 3, 4, 5, 6, 7, 8];

var isSubset = array.every(function(val) {
  return otherArray.indexOf(val) >= 0;
})

document.body.innerHTML = "Is array a subset of otherArray? " + isSubset;

本文标签: javascriptCheck if all items can be found in another arrayStack Overflow