0

I have two arrays and I'm trying to check if they contain the same data, without caring about the order.

Is there a simple and fast way to do this?

const array1 = ['foo', 'apple', 'bar'];
const array2 = ['bar', 'apple', 'foo'];



if (array1.length === array2.length && array1.every(function(value, index) {
    return value === array2[index]
  })) {
  console.log("Contain the same data");
} else {
  console.log("Do not contain the same data");
}
asdasf
  • 93
  • 7
  • 1
    Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – star67 Sep 07 '22 at 09:54

3 Answers3

2

You could perform these steps to achieve it

  • if two arrays are different in length, then they are not equal
  • sort both arrays by the same comparable function
  • check if all 2-element of the same index are equal

function compareArray(a, b) {
  if (a.length !== b.length) return false

  a.sort()
  b.sort()

  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) return false
  }

  return true
}

a = ["foo", "apple", "bar"]
b = ["bar", "apple", "foo"]
console.log("isEqual:", compareArray(a, b))

a = ["foo", "apple", "bar", "barz"]
b = ["bar", "apple", "foo"]
console.log("isEqual:", compareArray(a, b))

a = ["foo", "apple", "baz"]
b = ["bar", "apple", "foo"]
console.log("isEqual:", compareArray(a, b))
hgb123
  • 13,869
  • 3
  • 20
  • 38
1

try this

const isArrayEqual = (firstArray, secondArray) => {
  if (firstArray.length !== secondArray.length) return false

  firstArray.sort()
  secondArray.sort()

  return firstArray.every((elem, index) => elem === secondArray[index])
};

let a = ["foo", "apple", "bar"],
b = ["bar", "apple", "foo"]

console.log(isArrayEqual(a, b));

Arijit
  • 114
  • 1
  • 7
-1

既然都排序了,不如直接转成字符串比较

function compareArray(a, b) {
  if (a.length !== b.length) return false

  a.sort()
  b.sort()

  return a.join("")==b.join("")
}

a = ["foo", "apple", "bar"]
b = ["bar", "apple", "foo"]
console.log("isEqual:", compareArray(a, b))

a = ["foo", "apple", "bar", "barz"]
b = ["bar", "apple", "foo"]
console.log("isEqual:", compareArray(a, b))

a = ["foo", "apple", "baz"]
b = ["bar", "apple", "foo"]
console.log("isEqual:", compareArray(a, b))