skip to Main Content

I’d like to host a challenge,
I’ve made a JavaScript function that is very unoptimized and can be improved in a million ways,
Could you optimize it to the max?

function merge(array1, array2, array3, array4, array5){
  var result = [];
  var arrays = [array1, array2, array3, array4, array5];
  
  for (var i = 0; i < arrays.length; i++) {
    var array = arrays[i];
    for (var j = 0; j < array.length; j++) {
      var item = array[j];
      if (result.indexOf(item) === -1) {
        result.push(item);
      }
    }
  }
  
  return result;
}

const x = ['hi','hello','hey']
const y = ['apple','banana','orange']
const z = ['hie','helloe','heye']
const w = ['applei','bananai','orangei']
const e = ['hio','helloo','heyo']

console.log(merge(x,y,z,w,e));

Good luck optimizing it as best as you can!

I’ll give out a 2 hints:

  1. Instead of multiple parameters, you could turn it into one parameter that supports infinite arrays,

  2. Instead of using function(), there is an another way that uses less memory

2

Answers


  1. function merge(...arr) {
      const result = new Set();
      arr.forEach((item) => item.forEach((value) => result.add(value)));
      return Array.from(result);
    }
    
    const x = ['hi','hello','hey'];
    const y = ['apple','banana','orange'];
    const z = ['hie','helloe','heye'];
    const w = ['applei','bananai','orangei'];
    const e = ['hio','helloo','heyo'];
    const mergedArr = merge(x, y, z, w, e);
    
    console.log(mergedArr);
    Login or Signup to reply.
  2. Rest parameter syntax can be used to allow passing in any number of arrays. Then, we can flatten the parameter to concatenate all the arrays together. Finally, creating a Set from it and converting back to an array with spread syntax removes duplicates.

    const merge = (...arrs) => [...new Set(arrs.flat())];
    
    const x = ['hi','hello','hey']
    const y = ['apple','banana','orange']
    const z = ['hie','helloe','heye']
    const w = ['applei','bananai','orangei']
    const e = ['hio','helloo','heyo']
    
    console.log(merge(x, y, z, w, e));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search