如何使用减少,使用分解和递归来检查数组是否相等?

时间:2018-10-10 06:59:59

标签: javascript recursion ecmascript-6 reduce destructuring

您如何使用reduce助手,解构和递归检查两个数组是否相等?

const isEqual = (arr1, arr2) => {
  // use reduce helper to check arrays for equality, use destructuring and recursion
}

因此,显然isEqual([1,2,3], [1,2,3])应该返回true,而类似的isEqual(["hello", "there"], ["good", "morning"])应该返回false

2 个答案:

答案 0 :(得分:4)

您可以在比较之前使用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

答案 1 :(得分:2)

您可以对spread syntax ...采用递归方法,并通过检查元素的长度和长度来检查元素。

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"]));