- I have a single array of objects.
- The objects are different variations of this:
{
"animals": {
"name": "elephant",
"diet": "herbivore",
"color": "spotted",
"age": "12",
"numbers": ["11", "10", "24", "9"]
}
}
How to iterate through the collection and determine if there are differences between the "numbers" properties or "diet" properties? As in:
In the array, 50 elephant object's "diet" property read "herbivore", but one it reads "omnivore". Break out because it's different and report it.
Or as in:
In the array, 70 elephant object's "numbers" property are the same (even if some are out of order). Report they are the same.
What did I try?:
- Stringifying the objects and comparing them, but that won't work because I'm not trying to compare whole objects (just a few individual properties).
- I can make this work with a for loop, but it seems stupid overkill and not very efficient for a collection that potentially has hundreds of objects in it.
This is pseudo code, don't freak out:
var isValid = true;
//go through each element in the array
for(let i = 0, i < array.length, i++) {
//check if you have exceeded length of the array
if(i + 1 <= array.length) {
//sort the numbers
var sortedLowerNumbers = sortFunction(array[i].numbers);
var sortedhigherNumbers = sortFunction(array[i+1].numbers);
//compare equality
isValid = json.stringify(sortedLowerNumbers) === json.stringify(sortedhigherNumbers);
if(!isValid) {
break
}
}
}
My research
None of the questions seem applicable. They're seem to be either comparing multiple arrays rather than one or comparing entire JSON objects for equality rather than comparing individual properties.
Is there a smarter way to do this?