Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get ".push not a function"?

What's wrong with my code?

function longestConsec(strarr, k) {
  var currentLongest = "";
  var counter = 0;
  var outPut = [];

  if(strarr.length === 0 || k > strarr.length || k <= 0){
    return "";
  }
  for(var i = 0; i < strarr.length; i++){
    if(strarr[i] > currentLongest){
      currentLongest = strarr[i];
    }
  }
  while(currentLongest !== strarr[counter]){
    counter = counter + 1
  }
  for (var j = 0; j < k; j ++){
    outPut = outPut.push(strarr[counter + j]);
  }

  outPut = outPut.join("");

   return outPut;
}

I keep on getting "outPut.push is not a function".

like image 308
Braden Foltz Avatar asked Jan 23 '18 04:01

Braden Foltz


2 Answers

Array push functions returns the length of the array after pushing.

So, in your code

outPut = outPut.push(strarr[counter + j]);

outPut is now a number, not an array, so the second time through the loop, outPut no longer has a push method.

A simple solution is to change that line to

outPut.push(strarr[counter + j]);
like image 132
Jaromanda X Avatar answered Nov 12 '22 08:11

Jaromanda X


Array.push

adds one or more elements to the end of an array and returns the new length of the array.

And you have this line:

outPut = outPut.push(strarr[counter + j]);

You're adding an element to outPut.push(strarr[counter + j]); and then reassigning outPush to the length of the array.

You should only call the push method on the array and a new element will be added:

for (var j = 0; j < k; j ++){
    outPut.push(strarr[counter + j]);
}
like image 4
Ali Faris Avatar answered Nov 12 '22 09:11

Ali Faris