JavaScript find the longest palindrome compare arrays not working

Viewed 29

I am trying to work on various online exercises and I do not understand why my comparison of two arrays is not working. When I step through the Chrome debugger, I can see that the two arrays are equal.

The following is my code - given the string 'babbad':

const longestPalondrome = (str) => {
  if (str.length < 1) return -1;
  let tempStr,
    orgStrSlice = [];
  let tempArr = str.split('');
  let lngstPlndrm = 0;

  for (let i = 0; i < tempArr.length; i++) {
    tempStr = tempArr.slice(0, i + 1);
    orgStrSlice = [];

    tempStr.map((elem) => {
      orgStrSlice.push(elem);
    });

    // find palondrome
    if (orgStrSlice == tempStr.reverse().join('')) {
      if (tempStr.length >= lngstPlndrm || lngstPlndrm === 0) {
        lngstPlndrm = tempStr.length;
      }
    } else {
      console.log('not palondrome');
    }
  }

  return lngstPlndrm;
};

The following line is where I am not seeing why this is not working:

orgStrSlice == tempStr.reverse().join('')

You can see by the following screen shot that the two arrays are equal 'b','a','b', which should return true, followed by going into the conditional to set lngstPlndrm to the length of the string giving us the longest palindrome for this iteration of the loop, but yet it jumps straight to the else conditional. Whereas, in the first iteration, it found 'b' was equal to 'b'

screen shot of debugger

What am I doing wrong. As usual, thanks in advance

1 Answers

The below snippet show false...

console.log(["b", "a", "b"] == ["b", "a", "b"])

That is because the two arrays are not the same array, but two different arrays (with the same content... But at this point, it isn't what got compared).

To compare the content, you need to iterate...

let a = ["b", "a", "b"]
let b = ["b", "a", "b"]

console.log(a==b) // Still false

// This iterates all items of a and compare it to the corresponding item of b
// Then if there is no false, c is true
c = a.map((item, index)=>item==b[index]).indexOf(false)==-1

console.log(c) // True!

Related