JavaScript 中的两个数组的相等性
我们需要编写一个 JavaScript 函数,该函数接收两个数字数组(比如 first 和 second),并检查它们是否相等。
我们案例中的相等性将由以下两个条件之一决定:
如果数组包含相同的元素(不考虑它们的顺序),则它们相等。
如果第一个数组和第二个数组所有元素的总和相等。
例如:
[3, 5, 6, 7, 7] and [7, 5, 3, 7, 6] are equal arrays [1, 2, 3, 1, 2] and [7, 2] are also equal arrays but [3, 4, 2, 5] and [2, 3, 1, 4] are not equal
让我们编写此函数的代码:
示例
const first = [3, 5, 6, 7, 7];
const second = [7, 5, 3, 7, 6];
const isEqual = (first, second) => {
const sumFirst = first.reduce((acc, val) => acc+val);
const sumSecond = second.reduce((acc, val) => acc+val);
if(sumFirst === sumSecond){
return true;
};
// do this if you dont want to mutate the original arrays otherwise use
first and second
const firstCopy = first.slice();
const secondCopy = second.slice();
for(let i = 0; i < firstCopy.length; i++){
const ind = secondCopy.indexOf(firstCopy[i]);
if(ind === -1){
return false;
};
secondCopy.splice(ind, 1);
};
return true;
};
console.log(isEqual(first, second));输出
控制台中的输出将为:
true
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP