【问题标题】:create custom function to remove all occurrence of element in an array创建自定义函数以删除数组中所有出现的元素
【发布时间】:2021-10-22 11:52:50
【问题描述】:

我创建了以下函数来从数组中删除自定义元素:

 Array.prototype.removeElement=function(x){
    var index = this.indexOf(x);
    if (index !== -1) {
      this.splice(index, 1);
    }
};

它适用于以下数组:

var data = [1,2,3,4];
data.removeElement(2); //returns [1,3,4]

但是当我从某个元素中拥有多个项目时,它只会删除第一次出现。

var data = [1,2,3,4,2];
data.removeElement(2);
// returns [1,3,4,2] while I expect to get [1,3,4]

我知道我可以通过使用循环来做到这一点,但我很想知道是否有更简洁的代码?

【问题讨论】:

标签: javascript arrays function


【解决方案1】:

使用JS.filter()数组方法可以很方便。试试这段代码,


// Create a function in array prototype as 
Array.prototype.removeElement = function(x){
    return this.filter((elem)=>elem!==x);
}

这应该很有魅力,但我不认为。除了循环之外,还有其他方法可以做到这一点。

【讨论】:

    【解决方案2】:

    2 个解决方案:一个返回一个新数组,另一个就地执行

    解决方案 1:返回一个新数组

    您可以利用内置的filter 方法

    function removeAllOccurences (array, element) {
      return array.filter((ele) => ele !== element);
    }
    
    console.log(removeAllOccurences([1,2,3,4,3],3)); // [1,2,4]
    

    解决方案 2:就地使用递归

    function removeAllOccurences (array, element) {
      if (!array.includes(element)) {
        return array;
      } else {
        let index = array.indexOf(element);
        array.splice(index, 1);
        return removeAllOccurences(array, element);
      }
    }
    
    console.log(removeAllOccurences([1,2,3,4,3],3)); // [1,2,4]
    

    【讨论】:

      【解决方案3】:

      尝试使用 while 循环继续使用 splice 方法,直到该元素不再存在。

       Array.prototype.removeElement=function(x){
          var index = this.indexOf(x);
          if (index !== -1) {
            while (this.includes(x)) {
            index = this.indexOf(x);  
            this.splice(index, 1);
            }
          }
      
      }
         
      

      while 循环使用array.includes 方法来确定数组是否仍然包含该元素的值,如果是,它会将索引更新为下一个元素 x,之后它将像您的代码一样拼接该元素.当 array.includes 依次为 false 时 while 循环中断,从数组中删除所有等于 x 的元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-19
        • 2022-11-16
        • 2019-04-03
        • 2020-06-10
        • 2019-09-03
        • 1970-01-01
        • 2017-04-12
        • 1970-01-01
        相关资源
        最近更新 更多