0

Is there a much organised way to merge the different sized arrays to a single one, that each block will remain as an element just to sort them easily?

I've use nested for loops but still not sure if this is a proper way to do it.

function mergeArray(parameter){
  console.log(arguments.length); 
  let newArray = [];
  
  for (let i = 0 ; i<arguments.length; i++){
    for (let a = 0; a<arguments[i].length; a++){
      newArray.push(arguments[i][a]);   
    }  
  }
  

  return newArray.sort();
}

const shelf1 = ['apple', 'banana', 'orange', 'kiwi'];
const shelf2 = ['milk', 'egg', 'ketchup', 'sausage'];
const shelf3 = ['eggplant', 'cucumber', 'water', 'coke'];

console.log(mergeArray(shelf1, shelf2, shelf3))
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 1
    You can look at `Array.concat()` or you can merge using `newArray = [...shelf1, ...shelf2, ...shelf3]` – Kokodoko Jul 31 '22 at 21:53
  • Does this answer your question? [What is the most efficient way to concatenate N arrays?](https://stackoverflow.com/questions/5080028/what-is-the-most-efficient-way-to-concatenate-n-arrays) – pilchard Jul 31 '22 at 22:01
  • 1
    "*different sized arrays to a single one, that each block will remain as an element*" - can you show the exact result you want? – David Thomas Jul 31 '22 at 22:18
  • ["apple","banana","orange","kiwi","milk","egg","ketchup","sausage","eggplant","cucumber","water","coke"] is the result that I expect, since as I try to merge them the result seems like ['apple', 'banana', 'orange', 'kiwi' ], [ 'milk', 'egg', 'ketchup', 'sausage' ], [ 'eggplant', 'cucumber', 'water', 'coke' ] – Murat Ilyas Davarcı Jul 31 '22 at 22:35

1 Answers1

0

Use the spread operator to merge them together then .sort()

const shelf1 = ['apple', 'banana', 'orange', 'kiwi'];
const shelf2 = ['milk', 'egg', 'ketchup', 'sausage'];
const shelf3 = ['eggplant', 'cucumber', 'water', 'coke'];

const data = [...shelf1, ...shelf2, ...shelf3].sort();

console.log(data);
zer00ne
  • 41,936
  • 6
  • 41
  • 68