2

Trying to compare to arrays in JavaScript with the following approach.

 return stack1.forEach((v, i) => v === stack2[i]);

I want to get it working but it is returning undefined instead of true or false if the arrays are the same.

Here is the full code:

const backspace_compare = function(str1, str2) {
  let stack1 = [];
  let stack2 = [];
  for (let i = 0; i < str1.length; i++) {
    str1[i] === "#" ? stack1.pop() : stack1.push(str1[i]);
  }
  for (let i = 0; i < str1.length; i++) {
    str2[i] === "#" ? stack2.pop() : stack2.push(str2[i]);
  }
  return stack1.forEach((v, i) => v === stack2[i]);
};

Any help to fix the way I'm comparing the arrays using a similar approach would be really appreciated.

vrintle
  • 5,501
  • 2
  • 16
  • 46
mangokitty
  • 1,759
  • 3
  • 12
  • 17

1 Answers1

2

Here are some methods I use to compare two array in JS. The method I prefer usually is JSON.stringify.

However, I feel that your method is the fastest one, just you've to use .every() in place of forEach().

let stack1 = [1, 2, 3, 4];
let stack2 = [1, 2, 3, 4];

console.log('every compare:', stack1.every((v, i) => v === stack2[i]));
// or
console.log('toString compare:', stack1.toString() === stack2.toString());
// or
console.log('JSON compare:', JSON.stringify(stack1) === JSON.stringify(stack2));
// or
console.log('short compare:', stack1+'' === stack2+'');
vrintle
  • 5,501
  • 2
  • 16
  • 46