javascriptarraysarray-splice

Is there a way to splice out elements of an array and return the spliced array in one line?


If I have an array a = [1,2,3,4] and I want to return it with the 3 removed, there are two ways I can do it:

let b = [...a] // or a.slice()
b.splice(2,1)
return b

or

return [...a.slice(0,2), ...a.slice(3,4)]

Advantage of the second is that it's one line. Disadvantage is that it's verbose. I thought of writing a helper function that contains the logic of the first approach, so that I'd be able to call it in one line elsewhere.

Is there an alternative? Something like splice but that returns that spliced array rather than mutating it and returning the spliced-out elements.


Solution

  • Since you know the indicies you want to remove, you can use the Array.prototype.filter method.

    const a = [1,2,3,4];
    const b = a.filter((_, i) => i !== 2);
    console.log(b);

    If you need to remove a range, you can just do something like 2 < i || i > 3.

    .filter makes a copy of the array, copying the values where the callback function evaluates truthy and ignores the values where the callback function evaluates falsy.