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:
-
Instead of multiple parameters, you could turn it into one parameter that supports infinite arrays,
-
Instead of using function(), there is an another way that uses less memory
2
Answers
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.