如果两个数组包含精确的文本值,则匹配,JSON
Match if two arrays contains exact text values, JSON
目标:看看我是否可以匹配两个数组和 RETURN 布尔值 true
或 false
问题:我想问一下是否有更好的解决方案来匹配两个具有相同值的数组,例如
"arr1": ["hello, world, droids"],
"arr2": ["hello, there, Kenobi"]
我发现的一种方法来自另一个 SO 答案 here。但是当我们有 underscore 和 lodash 等实用程序库时,这种方法似乎太牵强了。
我的想法是这样的:
const __ = require('underscore')
if(__.difference(arr1, arr2).length > 0) {
console.log('not same')
} else {
console.log('same')
}
我对编程非常陌生,所以我不确定其中哪一个应该适用于生产,或者我的想法是否正确。
接下来我还将添加我找到的 SO 答案。
var areJSONArraysEqual = function(jsonArray1,
jsonArray2) {
if(jsonArray1.length===0||jsonArray2.length===0){
if(jsonArray1.length===0 && jsonArray2.length===0){
return true;
}else{
return false;
}
}
for(var i=0;i<jsonArray1.length;i++){
for ( var key in jsonArray1[i]) {
if(jsonArray1[i][key].length>1){
return areJSONArraysEqual(jsonArray1[i][key],jsonArray2[i][key])
}
if (jsonArray1[i][key] != jsonArray2[i][key]) {
return false;
}
}
}
return true;
};
您尝试做的似乎是深度平等比较。您可以使用 _.isEqual
在 Underscore(和 Lodash)中执行此操作。例如:
const _ = require('underscore');
const arr1 = ["hello, world, droids"];
const arr2 = ["hello, there, Kenobi"];
console.log(_.isEqual(arr1, arr2)); // false
目标:看看我是否可以匹配两个数组和 RETURN 布尔值 true
或 false
问题:我想问一下是否有更好的解决方案来匹配两个具有相同值的数组,例如
"arr1": ["hello, world, droids"],
"arr2": ["hello, there, Kenobi"]
我发现的一种方法来自另一个 SO 答案 here。但是当我们有 underscore 和 lodash 等实用程序库时,这种方法似乎太牵强了。
我的想法是这样的:
const __ = require('underscore')
if(__.difference(arr1, arr2).length > 0) {
console.log('not same')
} else {
console.log('same')
}
我对编程非常陌生,所以我不确定其中哪一个应该适用于生产,或者我的想法是否正确。
接下来我还将添加我找到的 SO 答案。
var areJSONArraysEqual = function(jsonArray1,
jsonArray2) {
if(jsonArray1.length===0||jsonArray2.length===0){
if(jsonArray1.length===0 && jsonArray2.length===0){
return true;
}else{
return false;
}
}
for(var i=0;i<jsonArray1.length;i++){
for ( var key in jsonArray1[i]) {
if(jsonArray1[i][key].length>1){
return areJSONArraysEqual(jsonArray1[i][key],jsonArray2[i][key])
}
if (jsonArray1[i][key] != jsonArray2[i][key]) {
return false;
}
}
}
return true;
};
您尝试做的似乎是深度平等比较。您可以使用 _.isEqual
在 Underscore(和 Lodash)中执行此操作。例如:
const _ = require('underscore');
const arr1 = ["hello, world, droids"];
const arr2 = ["hello, there, Kenobi"];
console.log(_.isEqual(arr1, arr2)); // false