0

When I am comparing two arrays from my state, if they are equal I want to change a third state boolean variable to "true". However when the two arrays are equal, the if statement I created to detect it does not return a "true".

I am doing this within a setInterval(), i dont know if that has anything to do with this problem...

class DisplaySort extends Component {
  constructor(props) {
    super(props);
    this.state = {
      array: [1, 2, 3],
      array2: [1, 2, 3],
      istrue: false,
     };
    this.compare = this.compare.bind(this);
};

render() {
   return (
     <div>
       <button onClick={this.compare}>Compare</button>
     </div>
    );
  }

compare(e) {
    this.myInterval = setInterval(() => {
      let a = this.state.array.slice();
      let b = this.state.array2.slice();
      if (a === b) {
        this.setState({ istrue: true });
        clearInterval(this.myInterval);
      }

(The set interval is being used for another operation in the application (aka there is an else statement after the if) but excluded for brevity's sake)

Jerry123
  • 67
  • 8
  • Define "comparing arrays". Are you trying to compare array *content*? You might want to reflect on what `===` means in JS if so. – Dave Newton Jun 18 '20 at 21:39
  • Comparing JS arrays is not that simple, check: https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript – Felipe Zavan Jun 18 '20 at 21:40
  • 1
    because `[] === []` = `false`, check this answer https://stackoverflow.com/questions/3115982/how-to-check-if-two-arrays-are-equal-with-javascript – ludwiguer Jun 18 '20 at 21:43
  • Arrays and Object are assigned by reference in JS. Thus you need to compare each element in the array against each element in the other array to see if they are equal. https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript – k.s. Jun 18 '20 at 21:44

2 Answers2

0

If you compare arrays that way , you will always get false, unless you check a === a

Here is a function to check equality between objects/arrays, also if nested:

function isEqual(value, other) {
    // Get the value type
    var type = Object.prototype.toString.call(value);

    // If the two objects are not the same type, return false
    if (type !== Object.prototype.toString.call(other)) {
        return false;
    }

    // If items are not an object or array, return false
    if (['[object Array]', '[object Object]'].indexOf(type) < 0) {
        return false;
    }

    // Compare the length of the length of the two items
    var valueLen = type === '[object Array]' ? value.length : Object.keys(value).length;
    var otherLen = type === '[object Array]' ? other.length : Object.keys(other).length;
    if (valueLen !== otherLen) {
        return false;
    }
    // Compare two items
    var compare = function (item1, item2) {

        // Get the object type
        var itemType = Object.prototype.toString.call(item1);

        // If an object or array, compare recursively
        if (['[object Array]', '[object Object]'].indexOf(itemType) >= 0) {
            if (!isEqual(item1, item2)) {
                return false;
            }
        }

        // Otherwise, do a simple comparison
        else {

            // If the two items are not the same type, return false
            if (itemType !== Object.prototype.toString.call(item2)) return false;

            // Else if it's a function, convert to a string and compare
            // Otherwise, just compare
            if (itemType === '[object Function]') {
                if (item1.toString() !== item2.toString()) return false;
            } else {
                if (item1 !== item2) return false;
            }

        }
    };

    // Compare properties
    if (type === '[object Array]') {
        for (var i = 0; i < valueLen; i++) {
            if (compare(value[i], other[i]) === false) return false;
        }
    } else {
        for (var key in value) {
            if (value.hasOwnProperty(key)) {
                if (compare(value[key], other[key]) === false) return false;
            }
        }
    }

    // If nothing failed, return true
    return true;

}

This is not written by me, I google it long ago.

CevaComic
  • 2,056
  • 2
  • 6
  • 12
0

You can simply use this:

  if(JSON.stringify(a) == JSON.stringify(b)){YOUR CODE HERE};

NOTE: this solution is good for your use case but not for complex array values.

rashi jain
  • 474
  • 3
  • 9