简体   繁体   中英

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?

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 .

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;  
}
JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())

Unified solution:

function compare(a, b){
      var isEqual = false;  
      if (Array.isArray(a) && Array.isArray(b) && a.length == b.length){
          a.sort();
          b.sort();
          var i;
          for (i = 0; i < arr1.length; i++){
              if (a[i] === b[i]){
                  isEqual = true;
              } else{
                  isEqual = false;
                  break;
              }
          }

      }
      return isEqual;
}

var arr1 = ["def", "abc"], arr2 = ["abc", "def"];
console.log(compare(arr2,arr1)); // gives 'true'

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

https://jsfiddle.net/ob7e5ye5/4/

function compare(arr1, arr2){
    var match = true
    if(arr1.length != arr2.length){
        match = false
    }
    arr1 = arr1.slice();
    arr1.sort();
    arr2.slice();
    arr2.sort();
    for(var i = 0; i < arr1.length; i++){
        if(arr1[i] != arr2[i]){
            match = false;
        }
    }
    return match;
}

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

I would suggest following ES6-oneliner

const compare = (a1, a2) =>
  (a1 = new Set(a1)) &&
  (a2 = new Set(a2)) &&
  a1.size === a2.size &&
  [...a1].every(v => a2.has(v));
  1. Remove duplicates by converting arrays to Sets (for compare(['a', 'a'], ['a', 'b']) should return false ).
  2. Length comparison (for compare(['a', 'b'], ['a', 'b', 'c']) should return false ).
  3. Check if the first set items are present in the second set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM