Search code examples
javascriptclassconcatenationtemplate-literalsspread-syntax

I want to populate an array [ ] , with a spread syntax by a given number of times


So I have a var size that may vary which counts how many arrays are passed in an argument.

concatenate(...arg){
 let size = arg.length ;
}

I want to use spread syntax by a number of times equal with that size ,more specific I want to concatenate all arrays, for example :

let arr1 = [1,2,3];
let arr2 = [3,2,1];
let arr3 = [4,5,6];
// unknown number of array

let finalArr = [...arr1,...arr2,...arr3,...etc];

So what I want to ask you is to replace the hardcoded finalArr, with a template that can take care of that for me?

What I tried so far :

// Arrays share the same content,ex : Arr : {content:[Arr(3)}
function concatenate(...arg){
 let size = arg.length;
 let arrays = arg;
 let tmplt = Arr(size+1).join(`Arr${size}`);
 let finalArr = [];
 while(size>=0){
  finalArr= [tmplt];
  size--;
}
return finalArr;
}

//input
let var1 = [{content:[2,9,10]}];
let var2 = [{content:[3,1,3]}];
let var3 = [{content:[9,1,8]}];
var1.concatenate(var2,var3);

// expected output
[2,9,10,3,1,3,9,1,8]

Finally, I try to reproduce the concat() method of Array within a class List that I made. The rules are : no Array.prototype.methods() allowed . Full code so far :

 class List {
  constructor(items){
   this.content = !items ? [] : items;
   this.size = this.length();
 }
 length(arg=0){
  let size = arg;
  if(!this.content[arg]){
   return size;
 }
  size++;
 return this.length(size);
 }
 append(arg){
  if(this.size ==0 && this.size == arg.size){
   this.content = new List();
   return this.content;
 }
 this.content = [...this.content,...arg.content] 
 return this.content;
 }
 concatenate(...arg){ 
  let test = arg;
  let size = 0;
  let final = [];
  while(test[size]!=undefined){
  // final += [...test[size].content];
  size++;
  let x = Array(size+1).join(`...test${size}.content`);
  while(size>=0){
    size--;
   
     }
    }

   }

  }

  let aList = new List([2,9,10]);

  let anotherList = new List([3,14,1]);

  let thirdList = new List([9,0,8]);

  aList.concatenate(anotherList,thirdList);

Solution

  • You can use a generator function which takes arrays delegates to each of the iterators. This allows you to flatten as many arrays as you want and can be used with spread notation:

    function* concat(...arrays) {
      for (const array of arrays)
        yield* array;
    }
    
    function concatenate(...arg){
     return [...concat(...arg)];
    }
    
    
    let arr1 = [1,2,3];
    let arr2 = [3,2,1];
    let arr3 = [4,5,6];
    
    let finalArr = concatenate(arr1, arr2, arr3);
    
    console.log(finalArr);
    .as-console-wrapper { max-height: 100% !important; }