【问题标题】:how to check if all item of array exist in another array如何检查数组的所有项目是否存在于另一个数组中
【发布时间】:2019-07-03 03:09:11
【问题描述】:

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

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

arr2 = [1,3];

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

【问题讨论】:

  • 只是让您知道,stackoverflow 不是代码编写服务。请附上您的尝试,以便我们为您提供帮助。
  • 我也有点困惑,根据您的要求,下面的答案是正确的。如果 array1 中的一个 id 不在第二个数组中,它将返回 false。这是正确的行为吗?因为根据您的问题,它是正确的。

标签: javascript arrays object


【解决方案1】:

我在下面列出了示例。一种使用 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));

【讨论】:

    【解决方案2】:
    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

    【讨论】:

    • 感谢您的帮助,但您的解决方案并不完全符合我的要求
    【解决方案3】:

    使用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)));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多