javascript - 检查一个数组中的至少一个值是否存在于另一个数组中失败

标签 javascript arrays

以下内容应返回 true,但报告为 false:

var array1 = ['fred'];
var array2 = ['sue', 'fred'];

var modified = [];

//create a new modified array that converts initials to names and vice versa 
    array1.forEach(function(element) {
            var index = array2.findIndex(el => el.startsWith(element[0]));
            if (index > -1) {
                modified.push(array2[index]);
                array2.splice(index, 1);
            } else {
                modified.push(element);
            }
    });

console.log(modified); // should be the same as array1
console.log(modified.some(v => array2.includes(v))); //false should be true

我正在尝试检查 array2 中是否至少存在一个modified值。

相反也是错误的:

console.log(array2.some(v => modified.includes(v))); //false should be true

JSFiddle

最佳答案

问题出在这一行:

array2.splice(index, 1);

您实际上是从 array2删除找到的项目,所以当然,如果您稍后在 array2 中查找该项目,它就会获胜不会被发现。观察:

var array1 = ['fred'];
var array2 = ['sue', 'fred'];
var modified = [];

//create a new modified array that converts initials to names and vice versa 
array1.forEach(function(element) {
  var index = array2.findIndex(el => el.startsWith(element[0]));
  if (index > -1) {
    modified.push(array2[index]);
    array2.splice(index, 1);
  } else {
    modified.push(element);
  }
});

console.log("modified: ", ...modified); // should be the same as array1
console.log("array2: ", ...array2);     // array2 has been modified

一个快速解决方案是在开始修改数组 array2 之前对其进行克隆,然后在克隆上进行工作:

var array1 = ['fred'];
var array2 = ['sue', 'fred'];
var modified = [];
var filtered = [...array2];

//create a new modified array that converts initials to names and vice versa 
array1.forEach(function(element) {
  var index = filtered.findIndex(el => el.startsWith(element[0]));
  if (index > -1) {
    modified.push(array2[index]);
    filtered.splice(index, 1);
  } else {
    modified.push(element);
  }
});

console.log(modified.some(v => array2.includes(v))); // true

关于javascript - 检查一个数组中的至少一个值是否存在于另一个数组中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172343/

相关文章:

java - 需要一种通用的方法来为 Windows 8 Store、Iphone 和 Android 编写数组

c++ - 分配数组时 operator new 的问题

arrays - 包含在数字范围内的组哈希键

Javascript 移动圆圈

javascript - Cordova OpenTok 集成 Chrome 问题

javascript - 如何创建 Facebook 时间线风格的日期滚动条?

javascript - 将包含一个元素的数组拆分为包含多个元素的数组

javascript - ES6 函数解构赋值为对象

javascript - 有没有办法将 AWS Athena 查询编程为每 15 分钟运行一次?

javascript - JavaScript 中有字典实现吗?