skip to Main Content

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


  1. 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.

    function removeItem(array, n) {
        return array.slice(0, n).concat(array.slice(n + 1));
    }
    
    Login or Signup to reply.
  2. 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:

    function removeItem(array, n) {
        return array.filter((item, index) => index !== n);
    }
    

    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 returns true. In this case, the callback function checks if the current index is equal to the given index n. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search