function arraysCommon(array1, array2) {
  return array1.filter(x => array2.includes(x));
}

此函数无法按我希望的方式工作.

所以基本上功能应该是

  • 第一个数组中的每个元素最多可以映射到第二个数组中的一个元素.
  • 每个数组中的重复元素都被视为单独的实体.
  • 第一个数组确定顺序

我试图循环遍历数组,并判断和比较每个数组中的重复数,但我似乎无法使逻辑正常工作.有没有其他方法来解决这个问题?

I've attached an image of two Venn diagrams that might clarify the difference I've attached an image of two Venn diagrams that might clarify the difference

推荐答案

不幸的是,它变得更加复杂,因为您需要知道您已经添加了哪些数字.在这种情况下,需要一个临时数组来保存结果.我们还需要跟踪数组中是否存在两次数字.

try 以下操作:

function arraysCommon(array1, array2) {
  //Copy array2 by duplicating and spreading the elements into another array.
  var copyArray2 = [...array2];
  //Temperary Array
  var temp = [];
  for (let x of array1) {
      //Check if the element is in the first array and not already added to the temp array
      if (copyArray2.includes(x)) {
          temp.push(x);
          //Remove item from copy array2 so it cannot be used anymore
          copyArray2.splice(copyArray2.indexOf(x), 1);
      }
  } 
  //Return the temp array
  return temp;
}

console.log(arraysCommon([1,2,3,2,1], [5,4,3,2,1]))
console.log(arraysCommon([1,2,3,2,1], [2,2,3,3,4]))

Javascript相关问答推荐

为什么我无法使用useMemo()停止脚本渲染?

为什么这个自定义组件会被放置在TR之外?

Next.js Next/Image图像隐含性有任何类型-如何修复?

如何才能拥有在jQuery终端中执行命令的链接?

Redux查询多个数据库Api reducerPath&

JS,当你点击卡片下方的绿色空间,而它是在它的背后转动时,

使用GraphQL查询Uniswap的ETH价格

XSLT处理器未运行

Ember.js 5.4更新会话存储时如何更新组件变量

在执行异步导入之前判断模块是否已导入()

在浏览器中触发插入事件时检索编码值的能力

Webpack在导入前混淆文件名

按下单键和多值

AJAX POST在控制器中返回空(ASP.NET MVC)

使用类型:assets资源 /资源&时,webpack的配置对象&无效

更新Redux存储中的对象数组

删除元素属性或样式属性的首选方法

是否可以将异步调用与useState(UnctionName)一起使用

使用Reaction窗体挂钩注册日历组件

构建器模式与参数对象输入