Reputation: 3593
Developing in MEAN stack. Express received and process req array parameters (initially string) and Mongoose returns object array property. I am facing very strange problem. Console.log outputs arrays as follows:
var arr1 = [ '5acde7adf7d2520e3b205970', '5acde7c0f7d2520e3b205971' ];
var arr2 = ["5acde7adf7d2520e3b205970","5acde7c0f7d2520e3b205971"];
first array is a JSON.parsed variable, second the property of MangoDB returned array property.
I need to compare arrays and if they different - perform operation.
Lodash isEqual function is always false. Lodash union the same as concat and filter, output arrays as follows (log output):
[ 5acde7adf7d2520e3b205970,
5acde7c0f7d2520e3b205971,
'5acde7adf7d2520e3b205970',
'5acde7c0f7d2520e3b205971' ]
If I check types of each array value then the first array values are objects the second are strings...
The only way I can property merge arrays is by preprocessing them like: JSON.parse(JSON.stringify(arr1)). Then all values are strings and merged properly as they shall:
[ '5acde7adf7d2520e3b205970', '5acde7c0f7d2520e3b205971' ]
Anybody faced this problem? Probably have some better ideas how to handle it
The best solution I found, for my problem, is to use map function to even array values. Ex:
arr2.map(String)
Upvotes: 0
Views: 125
Reputation: 371168
If it's always going to be an array of primitives, it should be quite easy to just compare each of their values like so:
const arr1 = [ '5acde7adf7d2520e3b205970', '5acde7c0f7d2520e3b205971' ];
const arr2 = ["5acde7adf7d2520e3b205970","5acde7c0f7d2520e3b205971"];
const isSame = (arr1, arr2) => {
if (arr1.length !== arr2.length) return false;
return arr1.every((arr1elm, i) => arr1elm === arr2[i]);
}
console.log(isSame(arr1, arr2));
The fact that one array may have been defined with double quotes and one with single quotes shouldn't affect anything, since they're already deserialized - it's still an array of strings underneath, not a string itself.
Upvotes: 2