Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare an array of strings in Javascript?

I want to see if two arrays of strings are equal.

Eg:

compare(["abc", "def"], ["def", "abc"])

should return true and similarly,

compare(["abc", "def"], ["def", "ghi"]) 

should return false.

What is the best way to do this?

like image 900
Abhijith S Avatar asked Feb 07 '23 23:02

Abhijith S


2 Answers

JavaScript doesn't have a Set or Multiset data structure (at least, not one with wide browser support), which is what you'd normally use for testing that two sets of items are the same regardless of order. So I recommend sorting the arrays and checking that their contents are equal. If you know the arrays contain only strings, you can check the items with simple equality:

function compare(array1, array2) {
  if (array1.length != array2.length) {
    return false;
  }

  array1 = array1.slice();
  array1.sort();
  array2 = array2.slice();
  array2.sort();

  for (var i = 0; i < array1.length; i++) {
    if (array1[i] != array2[i]) {
      return false;
    }
  }

  return true;
}

console.log(compare(["abc", "def"], ["def", "abc"])); // true
console.log(compare(["abc", "def"], ["def", "ghi"])); // false

For more general cases, you'll need a more complex definition of equality, and I recommend browsing the answers to this question.

like image 155
alltom Avatar answered Feb 11 '23 01:02

alltom


Naive algorithm: O(N^2)

function compare(array1, array2){
  for (var i = 0; i < array1.length; i++){
    if (array2.indexOf(array1[i]) < 0) return false;
  }
  return true;  
}

Better one: (uses sorting, O(NLOGN))

function compare(array1, array2){
  array1.sort();
  array2.sort();
  for (var i = 0; i < array1.length; i++){
    if (array1[i] !== array2[i]) return false;
  }
  return true;  
}
like image 37
Daniel Avatar answered Feb 10 '23 23:02

Daniel