Mangud
Mangud

Reputation: 25

Compare two words spelled backwards and forwards is same way in JS

var str = ("level");

arr = Array.from(str);

function repeat(arr) {

  let forward = arr.slice(0, arr.length);
  let backward = arr.reverse();

  console.log(forward);
  console.log(backward);

  if (forward === backward) {
    return true;
  } else {
    return false;
  }
};


var result = repeat(arr);

console.log(result);

I keep getting results as false.

Upvotes: 1

Views: 582

Answers (4)

Shreekesh Murkar
Shreekesh Murkar

Reputation: 605

Use following code :

str === [...str].reverse().join("") // result is true for 'level'

Upvotes: 0

DecPK
DecPK

Reputation: 25408

There are certain things that you can do with this

1) You can spread string in an array because str is a string and strings are iterable in JS.

let arr = [...str];

2) You can use spread in-place of slice to make it more readable

  let forward = [...arr];

3) Since reverse is in place, so you can spread it into a new array.

let backward = [...arr.reverse()];

4) You can have multiple options here first to use join and then compare because strings are primitive and compared with the value that is already answered. So you can also use every here:

forward.every((s, i) => s === backward[i]);

var str = "level";

let arr = [...str];

function repeat(arr) {
  let forward = [...arr];
  let backward = [...arr.reverse()];

  console.log(forward);
  console.log(backward);
  return forward.every((s, i) => s === backward[i]);
}

var result = repeat(arr);

console.log(result);

Upvotes: 1

vanowm
vanowm

Reputation: 10201

This is because you are comparing to different objects.

Convert them to string before compare:

var str = ("level");

arr = Array.from(str);

function repeat(arr) {

  let forward = arr.slice(0, arr.length).join("");
  let backward = arr.reverse().join("");

  console.log(forward);
  console.log(backward);

  if (forward === backward) {
    return true;
  } else {
    return false;
  }
};


var result = repeat(arr);

console.log(result);

The method of reversing the string is good, but you have many unnecesary steps. Here is a more optimized version:

var str = "level";

function repeat(forward) {

  const backward = forward.split("").reverse().join("");

  console.log(forward);
  console.log(backward);

  return forward === backward;
}


var result = repeat(str);

console.log(result);

Upvotes: 2

Tom Gionfriddo
Tom Gionfriddo

Reputation: 430

When you compare two arrays, you are not comparing their contents, but instead the array objects themselves. Because forward and backward are different arrays, they are not equal to each-other.

I'd suggest either looping through each element in both arrays and comparing them to each-other, or joining all the elements into strings and comparing those.

Upvotes: 2

Related Questions