Whats the best way to check if the arrays within an array are the same in my case?
var arrSession = [
{
type: '1',
usecase: [ '1' ]
},
{
type: '1',
usecase: [ '1' ]
}
];
var checkUsecase = arrSession.every(isSame);
function isSame(obj, index, arr) {
if (index === 0) {
return true;
} else {
return (
(obj.type === arr[index - 1].type) &&
(obj.usecase === arr[index - 1].usecase)
);
}
}
console.log('checkUsecase:');
console.log(checkUsecase);
The ‘usecase’ object within the array use to be a string ” and the isSame function used to work. But now they are arrays too. How to change the isSame function?
Here is a fiddle: https://jsfiddle.net/3j0odpec/
2
Answers
First we make some recursive compare function to walk nested arrays/objects. Then we run it over the array comparing that the current item is equal to the previous one.
While it’s a bit slower than comparing JSON.stringified array items of the OP’s data:
It wins with more complex objects:
For sameness / equality comparison of JSON conform data structures where performance is important as well one might consider the following recursive implementation of
isDeepDataStructureEquality
…