Alternative to .replace () so that it does not generate error in function with keys

2

I am creating a function that takes a nested array and returns it in a one-dimensional array, the problem is that I can not make it walk for cases in which keys {} are an element of the array, since the function .replace detect the laves, return "object". What alternatives do I have for this case?

function steamrollArray(arr) {
var str= arr.join().replace(/,/g,""); 
  //.replace no anda me cambia los {} 
var newArr= str.split("");
  
var lastArr=[];  
  for(var x=0;x<str.length;x++){
 
    if(isNaN(str.charAt(x))===false){
      lastArr[x]=parseInt(str.charAt(x));
    }else{
      lastArr[x]=str.charAt(x);
    }
     
    
  }
  
  
  return lastArr;
}

console.log(steamrollArray([1, {}, [3, [[4]]]]));
    
asked by victor.ja 21.08.2016 в 01:19
source

3 answers

1

Another possible solution (that if I'm not mistaken, does something similar to what I have put in the other answer, although in a longer way) would be to change the function so that it does the following:

  • Create an empty auxiliary array
  • Check if the parameter is an array; yes yes it is an array:
  • Go through it in a loop
  • Calling the function recursively for each element
  • And concatenating the result to the array of step 1
  • , if it is not:
  • Return an array with the element
  • Return the auxiliary array from step 1.
  • The code would be like this:

    function steamrollArray(arr) {
      
      var aux = [];
    
      if (arr.constructor === Array) {
        for (var x = 0; x < arr.length; x++) {
          aux = aux.concat(steamrollArray(arr[x]));
        }
      } else {
        return [arr];
      }
    
      return aux;
    }
    
    console.log(steamrollArray([1, {a:1}, [3, [[4]]]]));
        
    answered by 21.08.2016 / 04:44
    source
    2

    If you are looking for an alternative to replace, it would be to make a 'false replace' in the following way:

    String.prototype.falsoReplace=function(str, newstr) {
        return this.split(str).join(newstr);
    };
    
    var str="Bienvenido, JavaScript";
    str=str.falsoReplace('JavaScript', 'victor.ja');
    alert(str);

    Greetings.

        
    answered by 21.08.2016 в 03:24
    0

    Using ES6, Slikts puts here a really short solution to do what you're looking for:

    const flattenDeep = x => Array.isArray(x) ? [].concat(...x.map(flattenDeep)) : x
    

    that works great with the array you share:

    const steamrollArray = x => Array.isArray(x) ? [].concat(...x.map(steamrollArray)) : x;
    
    console.log(steamrollArray([1, {}, [3, [[4]]]]));
        
    answered by 21.08.2016 в 04:28