this function takes an array and a number, and returns a new array which has the item at array[number] removed. my code works, but is there a simpler/better practice way of doing this?
function removeItem(array, n) {
let newArr = []
for (let i=0;i<array.length;i++){
if (i!=n){
newArr.push(array[i])
}
}
return newArr
}```
2
Answers
The approach you’ve taken using a loop is valid and functional.
However, you can achieve the same result using array methods like slice() and concat(), which might be considered more concise and expressive.
Your code seems functional, but you can achieve the same result using array methods, which can make your code more concise and potentially easier to understand. You can use the
filter()
method to create a new array that excludes the item at the specified index. Here’s how you can do it:The
filter()
method creates a new array by iterating over each element in the input array. It includes elements for which the provided callback function returnstrue
. In this case, the callback function checks if the current index is equal to the given indexn
. If it’s not equal, the item is included in the new array. If it is equal, the item is excluded.This approach is more in line with modern JavaScript’s functional programming paradigm and can make your code more readable and maintainable.