Skip to content

Instantly share code, notes, and snippets.

@kartikpandey2
Created January 4, 2019 18:23
Show Gist options
  • Save kartikpandey2/a86ac1e889da7941d69f8381c85b8fb1 to your computer and use it in GitHub Desktop.
Save kartikpandey2/a86ac1e889da7941d69f8381c85b8fb1 to your computer and use it in GitHub Desktop.
Checks if array is similar or not
mapArray = (array) => {
const mapObj = {}
if(array.length === 0) {
return mapObj
}
for(let i=0; i<array.length; ++i) {
const value = array[i]
if(mapObj[value]) {
++mapObj[value]
}else{
mapObj[value] = 1
}
}
return mapObj
}
isObjectSimilar = (obj1, obj2) => {
const keysObj1 = Object.keys(obj1)
const keysObj2 = Object.keys(obj2)
if(keysObj1.length != keysObj2.length) {
return 0
}
for(let i=0;i<keysObj1.length;++i) {
const key = keysObj1[i]
if(obj1[key] != obj2[key]) {
return 0
}
}
return 1
}
isArraySimilar = (arr1, arr2) => {
if(arr1.length != arr2.length) {
return 0
}
const arr1Map = mapArray(arr1)
const arr2Map = mapArray(arr2)
return isObjectSimilar(arr1Map, arr2Map)
}
console.log(isArraySimilar([1, 2, 3], [1, 2, 3]))
console.log(isArraySimilar([1, 2, 3], [2, 1, 3])); //true
console.log(isArraySimilar([1, 2, 2], [2, 1, 1])); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment