Skip to content

Instantly share code, notes, and snippets.

@rileyjshaw
Created February 22, 2021 06:28
Show Gist options
  • Save rileyjshaw/fb51686dc86c7e9be8c788a1071d6123 to your computer and use it in GitHub Desktop.
Save rileyjshaw/fb51686dc86c7e9be8c788a1071d6123 to your computer and use it in GitHub Desktop.
Golfing to come up with a deep array comparison function for simple arrays.
// These comparison functions only work for arrays with the following child types:
//
// - Arrays
// - Values that can be directly compared with ===
//
// If your array contains functions or objects, go away!
// Solution 1: recursive comparison; 94 chars.
let f=Array.isArray,c=(x,y)=>f(y)&&x.length==y.length&&x.every((a,i)=>f(a)?c(a,y[i]):a===y[i])
// Solution 2: convert to strings before comparing; 40 chars.
let f=JSON.stringify,c=(x,y)=>f(x)==f(y)
// Usage example:
c([1,[2,3,[4]],5,[6,7]],[1,[2,3,[4]],5,[6,7]]) // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment