DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on • Updated on

Array same length challenge

I´m going to talk about a challenge i was given a few days ago at an interview.
The interviewer told me that my solution did not make sense to him and at the interview i could not make it work cause i was nervous but the same night i tried the challenge and indeed it worked.
Here is the challenge in question:
Given three parameters the first one being a function and the other two arrays, you have to return the given function with the two arrays and if you have to make sure the arrays are the same lenght and if the are not make them the same lenght as the shorter one and if they are the same just return it.

Here is my code:

const myFunc = (fn, a0, a1) => {
  let arr0 = [];
  let arr1 = [];
  if(a0.length < a1.length){
   for(let i = 0; i < a0.length; i++){
     arr0 += a0[i];
     arr1 += a1[i]
}
    return fn(arr0, arr1)
}else if(a1.length < a0.length){
   for(let i = 0; i < a1.length; i++){
         arr0 += a0[i];
         arr1 += a1[i] 
}
   return fn(arr0, arr1)
}else{
  for(let i = 0; i < a1.length; i++){
     arr0 += a0;
     arr1 += a1;
}
   return fn(arr0, arr1)
}
}
Enter fullscreen mode Exit fullscreen mode

In the example given the "fn" function will return an array that concatenates an both arrays given. So i am assuming that there is no need to do something else but just pass it as a parameter.
But just to make my self sure i actually code the function as follows:

const fn = (a0, a1) => {
  let concatenatedArr = [];
  concatenatedArr += [a0, a1]
  return [concatenatedArr]
}
Enter fullscreen mode Exit fullscreen mode

or even something like this

const fn = (a0, a1) => {
  let concatenatedArr = [] 
  concatenatedArr = a.concat(b)
  return concatenatedArr
}
Enter fullscreen mode Exit fullscreen mode

I understand maybe my approach is not the most efficient but i would not consider it wrong.

Hope someone found it helpful.

Lautaro

Top comments (0)