javascript - 检查是否使用原始列表修改了不可变列表
问题描述
我需要检查第二个不可变列表是否与原始列表相同,以便我可以设置一个布尔值。如何做到这一点?我尝试了以下方法
/**
* compare two lists
*/
public comparelists(){
const selectedItems = this.state?.originalgaparameterlist?.filter(item =>
this.gaparameterlist?.some(userItem => userItem.key === item.key)
);
if (selectedItems) {
this.globalParameterChanged = true;
}
else {
this.globalParameterChanged = false;
}
}
解决方案
/**
* compare two lists
*/
public comparelists(){
// a lot need to be changed ...
const selectedItems = this.state?.originalgaparameterlist?.filter(item =>
this.gaparameterlist?.some(userItem => userItem.key === item.key)
);
// `undefined` and `[]`
if (selectedItems && !!selectedItems.length) {
this.globalParameterChanged = true;
}
else {
this.globalParameterChanged = false;
}
}
function compareIsSameArray (A,B) {
if(!Array.isArray(A) || !Array.isArray(B)) return false
if(A.length !== B.length) return false;
const copyB = [...B]
A.forEach(a => {
const findIndex = copyB.indexOf(a)
if(findIndex >= 0) copyB.splice(findIndex, 1)
})
return !copyB.length
}
console.log(compareIsSameArray([], undefined)) // false
console.log(compareIsSameArray([1], [2,3])) // false
console.log(compareIsSameArray([], [])) // true
console.log(compareIsSameArray([1], [2])) // false
console.log(compareIsSameArray([1,3], [2,4])) // false
console.log(compareIsSameArray([1,3,5], [5,1,3])) // true
console.log(compareIsSameArray([1,3,3], [1,1,3])) // false
推荐阅读
- node.js - 延迟 ActiveMQ AMQP 1.0 的消息传递,_without_ JMS
- android - java.lang.IncompatibleClassChangeError,升级kotlin gradle插件到1.5.20后
- node.js - 当我要更新节点版本时面临警告但未能更新
- windows - PowerShell 调用-AzOperationalInsightsQuery 错误
- java - oracle JDK 8 中的 JavaFx 是否与 openjfx 8 版本相同?oracle jdk 8中的javafx和openjfx8有什么关系?
- hive - 重命名后如何从镶木地板文件中恢复旧列值?
- vaadin14 - 无法在 Vaadin 14.6.8 中导入 ViewFrame
- tcp - 当 TCP 连接只涉及 2 方时,为什么使用“3-way”这个词?
- python - 带有三个单引号的 Python setup.py entry_points 语法
- c# - 如何在 Y 轴上进行局部旋转