Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

So sánh 2 mảng chuỗi không phân biệt hoa thường và thứ tự JavaScript ES6

Viết hàm isEqual() nhận 2 chuỗi, kiểm tra có cùng ký tự (bỏ qua thứ tự và hoa/thường).

Ví dụ:

const first = 'Aavsg'; const second = 'VSAAg'; isEqual(first, second); //true

Cách 1: Dùng mảng - chuyển mảng, sort, join, so sánh.

Ví dụ

const first = 'Aavsg'; const second = 'VSAAg'; const stringSort = function(){ return this.split("").sort().join(""); } String.prototype.sort = stringSort; const isEqual = (first, second) => first.toLowerCase().sort() === second.toLowerCase().sort(); console.log(isEqual(first, second));

Cách 2: Dùng Map - đếm tần suất: -1 cho chuỗi 1, +1 cho chuỗi 2, cuối kiểm tra tất cả bằng 0.

Ví dụ

const first = 'Aavsg'; const second = 'VSAAg'; const isEqual = (first, second) => {    if(first.length !== second.length){       return false;    }    first = first.toLowerCase();    second = second.toLowerCase();    const map = {};    for(ind in first){       if(map[first[ind]]){ map[first[ind]]++; }else{ map[first[ind]] = 1; }       if(map[second[ind]]){ map[second[ind]]--; }else{ map[second[ind]] = -1; }    };    return Object.values(map).reduce((acc, val) => val === 0 && acc, true); }; console.log(isEqual(first, second));

Kết quả

Đầu ra console cho cả 2:

true