简体   繁体   English

JavaScript - 带有突变的过滤器数组

[英]JavaScript - Filter array with mutation

I want to filter a array by keeping the same array without creating a new one.我想通过保留相同的数组而不创建新数组来过滤数组。

with Array.filter() :使用Array.filter()

getFiltersConfig() {
  return this.config.filter((topLevelConfig) => topLevelConfig.name !== 'origin')
}

what is the best way to get the same result by filtering by value without returning a new array ?通过按值过滤而不返回新数组来获得相同结果的最佳方法是什么?

For completeness, I thought it might make sense to show a mutated array variant.为了完整起见,我认为展示一个变异的数组变体可能是有意义的。

Below is a snippet with a simple function mutationFilter , this will filter the array directly, notice in this function the loop goes in reverse, this is a technique for deleting items with a mutated array.下面是一个带有简单函数mutationFilter的片段,这将直接过滤数组,注意在这个函数中循环是相反的,这是一种删除带有变异数组的项目的技术。

Also a couple of tests to show how Array.filter creates a new array, and mutationFilter does not.还有一些测试来展示Array.filter如何创建一个新数组,而mutationFilter没有。

Although in most cases creating a new array with Array.filter is normally what you want.尽管在大多数情况下,使用Array.filter创建一个新数组通常是您想要的。 One advantage of using a mutated array, is that you can pass the array by reference, without you would need to wrap the array inside another object.使用变异数组的一个优点是,您可以通过引用传递数组,而无需将数组包装在另一个对象中。 Another advantage of course is memory, if your array was huge, inline filtering would take less memory.另一个优势当然是内存,如果你的数组很大,内联过滤会占用更少的内存。

 let arr = ['a','b','a']; let ref = arr; //keep reference of original arr function mutationFilter(arr, cb) { for (let l = arr.length - 1; l >= 0; l -= 1) { if (!cb(arr[l])) arr.splice(l, 1); } } const cond = x => x !== 'a'; const filtered = arr.filter(cond); mutationFilter(arr, cond); console.log(`ref === array -> ${ref === arr}`); console.log(arr); console.log(`ref === filtered -> ${ref === filtered}`); console.log(filtered);

You could define you custom method like so:您可以像这样定义自定义方法:

 if(!Array.prototype.filterThis){ Array.prototype.filterThis = function (callBack){ if(typeof callBack !== 'function') throw new TypeError('Argument must of type <function>'); let t = [...this]; this.length = 0; for(let e of t) if(callBack(e)) this.push(e); return this; } } let a = [1,2,3,4,5,5,1,5]; a.filterThis(x=>x!=5); console.log(a);

Warning: Be very cautious in altering built in prototypes.警告:在更改内置原型时要非常谨慎。 I would even say unless your making a polyfill don't touch.我什至会说,除非你制作一个 polyfill,否则不要碰。 The errors it can cause can be very subtle and very hard to debug.它可能导致的错误非常微妙并且很难调试。

Not sure why would you want to do mutation but if you really want to do it, maybe assign it back to itself?不确定为什么要进行突变,但如果您真的想做,也许可以将其分配回自身?

 let arr = ['a','b','a']; arr = arr.filter(x => x !== 'a'); console.log(arr)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM