首页 > 解决方案 > 检查是否使用原始列表修改了不可变列表

问题描述

我需要检查第二个不可变列表是否与原始列表相同,以便我可以设置一个布尔值。如何做到这一点?我尝试了以下方法

/**
     * 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;
        }
    }

标签: javascript

解决方案


/**
     * 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


推荐阅读