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