Array.prototype.toggle

Scott Rudiger scottrudiger at gmail.com
Fri Feb 7 21:36:20 UTC 2020


I believe this wouldn't result in the OP's desired results since the
filtered array is no longer the same length as the original array:

```js
var toggle = (arr, el) => Object.assign(arr, arr.filter(n => n !== el));

toggle([1, 2, 3, 2, 1], 1); // [2, 3 ,2, 2, 1]
```

Here's a helper function that would work (and also push the element if it's
not included in the original array):

```js
var toggle = (arr, el) => {
var len = arr.length;

for (var i = 0; i < arr.length; i++)
if (arr[i] === el)
arr.splice(i--, 1);

if (arr.length === len)
arr.push(el);

return arr;
};

var a = toggle([1, 2, 3, 2, 1], 1); // mutates the original array removing
1 => [2, 3, 2]
toggle(a, 1); // mutates the original array adding 1 => [2, 3, 2, 1]
```


On Fri, Feb 7, 2020 at 11:26 AM Herby Vojčík <herby at mailbox.sk> wrote:

> On 7. 2. 2020 13:11, Scott Rudiger wrote:
> > `Array.prototype.filter` seems more versatile (although it doesn't
> > mutate the original array) since it removes elements based on a function:
> >
> > ```js
> > [1, 2, 3, 2, 1].filter(n => n !== 1); // [2, 3, 2]
> > ```
>
> But what if one wants to mutate in-place. Would this work?
>
>    Object.assign(arr, arr.filter(n => n !== 1))
>
> If not, maybe there can be
>
>    aCollection.replaceWith(anIterable)
>
> Herby
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20200207/a6d55fd5/attachment.html>


More information about the es-discuss mailing list