[英]How to check array equality with reduce, using destructuring and recursion?
How would you check two arrays for equality using the reduce helper, destructuring and recursion? 您如何使用reduce助手,解构和递归检查两个数组是否相等?
const isEqual = (arr1, arr2) => {
// use reduce helper to check arrays for equality, use destructuring and recursion
}
So obviously isEqual([1,2,3], [1,2,3])
should return true
for example and something like isEqual(["hello", "there"], ["good", "morning"])
should return false
. 因此,显然
isEqual([1,2,3], [1,2,3])
应该返回true
,例如isEqual(["hello", "there"], ["good", "morning"])
应该返回false
。
You can stringify the arrays by using JSON.stringify()
before the comparison: 您可以在比较之前使用
JSON.stringify()
对数组进行字符串化:
const isEqual = (arr1, arr2) => { var flag = JSON.stringify(arr1)==JSON.stringify(arr2)? true : false; return flag; } console.log(isEqual([1,2,3], [1,2,3])); //true console.log(isEqual(["hello", "there"], ["good", "morning"])); //false console.log(isEqual([1, '2', 3], [1,2,3])); //false
You could take a recursive approach with spread syntax ...
and a check for the elements and by checking the length'. 您可以采用具有扩展语法的递归方法
...
并检查元素并通过检查长度'。
const isEqual = ([v, ...a], [w, ...b]) => { return v === w && a.length === b.length && (a.length === 0 || isEqual(a, b)); } console.log(isEqual([1, 2], [1, 2, 3])); console.log(isEqual([1, 2, 3], [1, 2, 3])); console.log(isEqual([1, 2, 3, 4], [1, 2, 3])); console.log(isEqual(["hello", "there"], ["good", "morning"]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.