gdf*_*dfg 1 javascript arrays ecmascript-6
我想比较两个字符串数组,但不区分大小写且独立.
例如:
['a', 'b', 'c'] === ['A', 'c', 'B'] -> TRUE
['a', 'b', 'c'] === ['a', 'b', 'd'] -> FALSE
Run Code Online (Sandbox Code Playgroud)
TRUE当它们具有相同的长度和相同的值(不区分大小写['A'] === ['a'] -> true)且独立时,关于排序['a', 'b'] === ['b', 'a'] -> true.
我现在做的是:
areEqual = (arr1, arr2) => {
const equalLength = arr1.length === arr2.length;
return arr2.every(arr2Item => {
return arr1.includes(arr2Item.toLowerCase());
}) && equalLength;
};
Run Code Online (Sandbox Code Playgroud)
,但这是case sensitive.
我使用JS, ES6带React.
您可以将字符串规范化为小写,并使用a Set来检查值.
function compare(a, b) {
const lower = s => s.toLowerCase();
return b
.map(lower)
.every(Set.prototype.has, new Set(a.map(lower)));
}
console.log(compare(['a', 'b', 'c'], ['A', 'c', 'B'])); // true
console.log(compare(['a', 'b', 'c'], ['a', 'b', 'd'])); // false
console.log(compare(['a', 'b', 'c'], ['a', 'c'])); // trueRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
397 次 |
| 最近记录: |