Javascript Array sameStructureAs(other)

Description

Javascript Array sameStructureAs(other)


Array.prototype.sameStructureAs = function (other) {
  const stringify = a => `[${a.map(b => Array.isArray(b) ? stringify(b) : '|').join('')}]`
  return Array.isArray(other) ? stringify(this) === stringify(other) : false
}

Javascript Array sameStructureAs(other)

Array.prototype.sameStructureAs = function (other) {
  if ( this.length !== other.length ) return false;
  
  for ( var i = 0; i < this.length; i++ ){
    if (Array.isArray(this[i]) && Array.isArray(other[i])) {
      if (!this[i].sameStructureAs(other[i])) return false;
    } else if (Array.isArray(this[i]) || Array.isArray(other[i])){
      return false;
    }/*from  ww  w .  j av a  2s  .  co m*/
  }
  return true;
};

Javascript Array sameStructureAs(other)

Array.prototype.sameStructureAs = function (other) {
  var helper = function(a,b){
    if(!isArray(b))
      return false;
    for(i in a){/* w w w .java 2s  .co m*/
      if(b[i]===undefined || isArray(a[i])!==isArray(b[i]) || isArray(a[i]) && !a[i].sameStructureAs(b[i]))
        return false;
      }
    return true;
    }
  return helper(this, other) && helper(other, this);
};

Javascript Array sameStructureAs(other)

Array.prototype.sameStructureAs = function (other) {
  if(!Array.isArray(other) && this.length != other.length) return false;
  
  var result = ''; 

  function inner(arr) {

   for (var i = 0; i < arr.length; i++) {
      if (Array.isArray(arr[i])) {
      result += arr[i].length + ':';
          if(arr[i].length != 0) inner(arr[i]);
      }/*  w w w . j  a va 2  s. c  o  m*/
  
      result += 'N';
  
    }
   
     return result;
  }
  var a = inner(this);
  result = '';
  var b = inner(other);
  return a == b ? true : false;
}

Javascript Array sameStructureAs(other)

// https://www.codewars.com/kata/520446778469526ec0000001

Array.prototype.sameStructureAs = function (other) {   
 if (!Array.isArray(other)) return false;

 function transform(array) {
  return array.map(item => Array.isArray(item) ? [transform(item)] : "0");
 }
   //from  ww  w . j a  va  2s.c  o  m
 return JSON.stringify(transform(this)) === JSON.stringify(transform(other));
};

console.log([ 1, [ 1, 1 ] ].sameStructureAs( [ 2, [ 2, 2 ] ] ));
console.log([ [ [ ], [ ] ] ].sameStructureAs( [ [ [ ], [ ] ] ] ))



PreviousNext

Related