Javascript 反应过滤器,然后交换数组元素
Javascript 反应过滤器,然后交换数组元素,javascript,reactjs,Javascript,Reactjs,const filterData=apiData.filter(数据=>{ 返回此.shouldDisplayItem( 数据, [this.state.searchValue], this.state.filterKeyValue ); }).filter(i=>i.vid), x=0, y=apiData.map(i=>i.vid.indexOf(markerId); A[x]=A.拼接(y,1,A[x])[0]您可以使用过滤器过滤出阵列,然后使用交换 Array.prototype.sw
const filterData=apiData.filter(数据=>{
返回此.shouldDisplayItem(
数据,
[this.state.searchValue],
this.state.filterKeyValue
);
}).filter(i=>i.vid),
x=0,
y=apiData.map(i=>i.vid.indexOf(markerId);
A[x]=A.拼接(y,1,A[x])[0]
您可以使用过滤器
过滤出阵列,然后使用交换
Array.prototype.swap=函数(swapFirst,swapSecond){
var x=this.findIndex(a=>a==swapFirst);
变量y=this.findIndex(a=>a==swapSecond);
var b=此[y];
此[y]=此[x];
这个[x]=b;
归还这个;
}
var apiData=[0,1,2,3,4,5,6,7,8,9];
var filtered=apiData.filter(a=>a>2).swap(7,8);
console.log(过滤)代码>您可以使用reduce()简单地完成它。
因此,在reduce函数中,我首先检查value>2
条件
- 如果通过,我将检查
值===7
或值===8
如果其中任何一个匹配,我将根据您的需要更改值。如果不匹配,我将直接推入输出数组李>
- 如果
value>2
失败,我不会在输出数组中推送该值
设arr=[0,1,2,3,4,5,6,7,8,9];
让op=arr.reduce((op,cur)=>{
如果(cur>2){
如果(cur==7)操作推送(8);
如果(电流===8)操作推送(7);
else op.push(当前);
}
返回op;
},[])
控制台日志(op)代码>
在第二个过滤器上,我交换了两个数组对象
Array.prototype.filter应该只过滤数组中的元素,而不是映射/交换元素
我们可以一次过滤两次相同的数组吗
是的,例如:
[1, 2, 3, 4, 5].filter((e, idx) => e + 1 === idx).filter(e => e%2 === 0)
可替换为:
[1, 2, 3, 4, 5].filter((e, idx) => e + 1 === idx && e%2 === 0)
是的,您可以进行函数链接。