0

Why Array.push doesnt work inside Nested For Loop? But it works if I replace 2nd for Loop with forEach

var longestCommonPrefix = function (strs) {
    if (strs.length === 1) {
        return strs.join('')
    }

    let reference = strs[0].split('');
    let answer = [];
    let final = [];
    for (let i = 1; i < strs.length; i++) {
        let check = strs[i].split('')
        for (let x = 0; x < reference.length; x++) {
            if (reference[x] === check[x]) {
                answer.push(check[x]) //WHY THIS WONT WORK?
            } else return
        }
        reference = answer
    }

    console.log(answer)
};

longestCommonPrefix(["flower", "flow", "flight"]);

2
  • What's your expected output? Commented Aug 14, 2021 at 7:05
  • Expected Answer ["f", "l"], But my point is why cant Ipush elements inside the Array? Commented Aug 14, 2021 at 9:08

1 Answer 1

1

return is used to exit the function, use break to only exit the loop

var longestCommonPrefix = function(strs) {
  if (strs.length === 1) {
    return strs.join('')
  }

  let reference = strs[0].split('');
  let answer = [];
  let final = [];
  for (let i = 1; i < strs.length; i++) {
    let check = strs[i].split('')    
    for(let x = 0 ; x<reference.length ; x++){
      if(reference[x] === check[x]){
        answer.push(check[x]) //WHY THIS WONT WORK?
      }else break
    }
    reference = answer
  }
  
  console.log(answer)
};

longestCommonPrefix(["flower", "flow", "flight"])

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.