search

Home  >  Q&A  >  body text

There is a problem when the getFirstHalf function returns the result

I'm developing a function that takes an array and returns the first half of the array, but before returning it calls itself until the length of the array is 1:

const getFirstHalf = function (array) {
  const firstHalf = [];
  for (let i = 0; i < Math.trunc(array.length / 2); i++) {
    firstHalf.push(array[i]);
  }
  if (firstHalf.length !== 1) {
    getFirstHalf(firstHalf);
  }
  return firstHalf;
};

Everything works as expected, until the row where the result is returned, the array gets the previous value until it is the first half of the first state of the array. Hope you understand what I mean.

For example:

const myArray = [1,2,3,4,5,6,7,8];
console.log(getFirstHalf(numbers));

I expected to get [1] as result, but I got [1,2,3,4].

P粉311617763P粉311617763438 days ago794

reply all(1)I'll reply

  • P粉009186469

    P粉0091864692023-09-23 00:09:10

    You need to return the result from the recursion:

    Will

    getFirstHalf(firstHalf);
    

    changed to

    return getFirstHalf(firstHalf);
    

    reply
    0
  • Cancelreply