function trimArray(array) { const firstItem = array[0]; const lastItem =…
- User
function trimArray(array) { const firstItem = array[0]; const lastItem = array[array.length - 1];
if (!firstItem || !lastItem) { return array.slice(1, -1); } if (!firstItem) { return array.slice(1); } if (!lastItem) { return array.slice(0, -1); }
return array; }
console.log(trimArray([0, 1, 2, 3, 4, 5, 0, '']));
This has to slice the 0 behind the last item as well, make it trims them correctly, all the falsy values at the beginning and at the end should be trimmed
- Assistant
To trim all falsy values from both the beginning and the end of an array, you can iterate from the start to find the first truthy element and from the end to find the last truthy element. Then, use these indices to slice the array accordingly. Here's an improved version of your function that accomplishes this: