Find missing element by comparing 2 arrays in Javascript(通过比较 Javascript 中的 2 个数组来查找缺失的元素)
问题描述
由于某种原因,我很难解决这个问题.我需要这个 JS 函数,它接受 2 个数组,比较 2,然后返回缺少元素的字符串.例如.查找 currentArray 中缺少的元素,该元素在前一个数组中存在.
For some reason I'm having some serious difficulty wrapping my mind around this problem. I need this JS function that accepts 2 arrays, compares the 2, and then returns a string of the missing element. E.g. Find the element that is missing in the currentArray that was there in the previous array.
function findDeselectedItem(CurrentArray, PreviousArray){
var CurrentArrSize = CurrentArray.length;
var PrevousArrSize = PreviousArray.length;
// Then my brain gives up on me...
// I assume you have to use for-loops, but how do you compare them??
return missingElement;
}
提前致谢!我不是要代码,但即使只是朝着正确的方向推动或提示可能会有所帮助......
Thank in advance! I'm not asking for code, but even just a push in the right direction or a hint might help...
推荐答案
这应该可行.您还应该考虑数组元素实际上也是数组的情况.indexOf 可能无法按预期工作.
This should work. You should also consider the case where the elements of the arrays are actually arrays too. The indexOf might not work as expected then.
function findDeselectedItem(CurrentArray, PreviousArray) {
var CurrentArrSize = CurrentArray.length;
var PreviousArrSize = PreviousArray.length;
// loop through previous array
for(var j = 0; j < PreviousArrSize; j++) {
// look for same thing in new array
if (CurrentArray.indexOf(PreviousArray[j]) == -1)
return PreviousArray[j];
}
return null;
}
这篇关于通过比较 Javascript 中的 2 个数组来查找缺失的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过比较 Javascript 中的 2 个数组来查找缺失的元素
基础教程推荐
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
