DEV Community

Lautaro Suarez
Lautaro Suarez

Posted on • Edited on

1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay