Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: destructive array.filter()? [duplicate]

Is there a good functional style way of deleting elements in a JS array while looping?

I know filter can be used to create a new array:

var newArr = arr.filter((x) => x.foo > bar)

But is there a way to actually delete the elements from arr as you go?

BTW: I can't reassign, this is a data object on Vue component, so I need to update, not reassign.

BTW2: This is not a duplicate. I know how to do it with normal JS iteration. I am looking for a functional way, and the referenced answer doesn't contain that. Not a dupe.

like image 278
mtyson Avatar asked Oct 16 '22 17:10

mtyson


1 Answers

Simply re-assign the Array

let arr = [1,2,3,4,5];
arr = arr.filter(v => v < 3);
console.log(arr);
like image 157
KooiInc Avatar answered Oct 20 '22 22:10

KooiInc