2021/06/16

Compare two arrays is equal in JavaScript

在 PHP 中,可以簡單使用比較運算子比對兩個陣列。

$a = ['a', 'b', 'c'];
$b = ['a', 'b', 'c'];
var_dump($a === $b); // true

甚至排序不一樣透過 sort 也可以解決。

$a = ['a', 'b', 'c'];
$b = ['a', 'c', 'b'];
var_dump(sort($a) === sort($b)); // true

但在 js 的世界不行。

const a = [
'a',
'b',
'c'
];
const b = [
'a',
'b',
'c'
];
console.log(a == b); // false
console.log(a === b); // false

在網路上看到一個解法挺好的,記錄一下。

const a = [
'a',
'b',
'c'
];
const b = [
'a',
'b',
'c'
];
const result = a.sort().every((value, index) => {
return value === b.sort()[index];
});
console.log(result); // true

寫成 prototype 就是。

const a = [
'a',
'b',
'c'
];
const b = [
'a',
'b',
'c'
];
Array.prototype.equals = function (array) {
return this.sort().every((value, index) => {
return value === array.sort()[index];
});
}
console.log(a.equals(b)); // true