javascript - Comparing values between two arrays -


i'm trying set function checks if word or text palindrome. that, splits text every letter element of new array, takes rid of white spaces , makes reverse array. checks if every element of 2 arrays, @ same positions, equal. if not returns false, if yes returns true. here function:

function palindrome(str) {    var low = str.tolowercase();    var newarray = low.split("");    var nospace = newarray.filter(function(val) {      return val !== " ";    });    var reverse = nospace.reverse();        function check (a, b) {      console.log(`checking '${a}' against '${b}'`);      var partial;      var result = 1;      (var = 0; < a.length; i++) {        console.log(`comparing '${a[i]}' , '${b[i]}'`);        if (a[i] !== b[i]) {          result = 0;        } else {          partial = 1;          result *= partial;        }      }      return result;    }        var result = check(nospace, reverse);    if (result == 1) {      return true;    } else {      return false;    }           }      palindrome("r y e");

i don't know what's wrong seems function keeps on returning true value no matter word or text pass function. wrong that?

your issue seems because reverse() changes actual array well. doing

var reverse = nospace.reverse(); 

will reverse nospace , assign reference on variable reverse. is, both arrays same (reversed) array.

to bypass that, i've used .slice() create copy of original array, , called .reverse() on new array, ridding of conflicts.

here's working snippet of looks like:

function palindrome(str) {      var str_array = str.tolowercase().split("");      var no_space = str_array.filter(function(val) {          return val !== " ";      });        // applying '.slice()', create new array      // reference can reversed , assigned      // 'reverse' variable      var reverse = no_space.slice().reverse();        function check(a, b) {          var partial;          var result = 1;          for(var i=0; < a.length; i++) {              if(a[i] !== b[i]) {                  // don't need keep                  // comparing two,                  // failed                  return 0;              } else {                  // i've kept part though                  // don't know                  // intended                  partial = 1;                  result *= partial;              }          }          return result;      }      return check(no_space, reverse) === 1;  }    console.log(palindrome("a b a"));  console.log(palindrome("r y e"));


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -