如何检查数组的所有项目是否在另一个数组中

时间:2019-07-03 03:09:11

标签: javascript arrays object

我确实有2个数组 第一个数组是:

arr1 = [
  {
    id: 1,
    name: "aa"
  },
  {
    id: 2,
    name: "aa"
  },
  {
    id: 3,
    name: "aa"
  }
];

arr2 = [1,3];

我想检查arr1中的所有object.id是否存在于arr2中

3 个答案:

答案 0 :(得分:0)

我在下面列出了示例。一种使用Includes,另一种使用indexof。 Internet Explorer不支持包含https://caniuse.com/#feat=array-includes,因此,如果需要所有浏览器的支持,请使用indexof。参见下面的代码。

var arr1 = [
  {
    id: 1,
    name: "aa"
  },
  {
    id: 2,
    name: "aa"
  },
  {
    id: 3,
    name: "aa"
  }
];

var arr2 = [1,3];

// Using Includes
function compareArrays(arr1, arr2) {
	for(var i = 0; i < arr1.length; i++) {
		if(!arr2.includes(arr1[i].id)) {
			return false;
		}
	}
	return true;
}

// One thing to note, includes is not supported by internet explorer, so you have to use indexof. Example below.
function compare(arr1, arr2) {
	for(var i = 0; i < arr1.length; i++) {
		if(arr2.indexOf(arr1[i].id) === -1) {
			return false;
		}
	}
	return true;
}

console.log(compareArrays(arr1, arr2));
console.log(compare(arr1, arr2));

答案 1 :(得分:-1)

const exists = arr1.reduce((carry, item) => {
  if (carry === false) {
    return carry;
  };
  return arr2.includes(item.id);
});

更多关于减少这里 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

答案 2 :(得分:-1)

使用every

arr1 = [{
    id: 1,
    name: "aa"
  },
  {
    id: 2,
    name: "aa"
  },
  {
    id: 3,
    name: "aa"
  }
];

arr2 = [1, 3];

console.log(arr1.every(({
  id
}) => arr2.includes(id)));