首页 > 解决方案 > 反应过滤器然后交换数组元素

问题描述

  const filterData = apiData.filter(data => {
      return this.shouldDisplayItem(
        data,
        [this.state.searchValue],
        this.state.filterKeyValue
      );
    }).filter(i => i.vid),
     x = 0,
      y = apiData.map(i => i.vid).indexOf(markerId);
  A[x] = A.splice(y, 1, A[x])[0];

例如,我有一个array = [0,1,2,3,4,5,6,7,8,9]. 首先我想过滤大于 2 的值,然后我想通过索引号交换 7 和 8。

在最初的原始项目中,我正在做一些过滤器而不是第二个过滤器我正在交换两个数组对象我们可以一次过滤两次相同的数组吗?

标签: javascriptreactjs

解决方案


您可以使用filter过滤掉数组,然后swap使用prototype

Array.prototype.swap = function (swapFirst,swapSecond) {
var x = this.findIndex(a=> a === swapFirst);
var y = this.findIndex(a=> a === swapSecond);
var b = this[y];
this[y] = this[x];
this[x] = b;
return this;

}


var apiData = [0,1,2,3,4,5,6,7,8,9];
var filtered= apiData.filter(a=> a > 2).swap(7,8);
console.log(filtered);


推荐阅读