0

I need to check if a second immutable list is same as that of the original list,so that i can set a boolean value.How can this be done? I tried the following approach

/**
     * 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;
        }
    }
Nishant
  • 54,584
  • 13
  • 112
  • 127
techno
  • 6,100
  • 16
  • 86
  • 192
  • Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Nishant Feb 25 '21 at 11:15

1 Answers1

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