【问题标题】:How does one remove number values and empty values from an array?如何从数组中删除数值和空值?
【发布时间】:2021-04-10 09:06:42
【问题描述】:

作为我 nightwatchjs 测试的一部分,我有一个动态数组(在一个对象中)需要一些调整。

我当前的数组是这样的;

{ GenericColour:    [ 'Black',
     5059,
     'White',
     3610,
     'Grey',
     3281,
     'Blue',
     2131,
     'Silver',
     1408,
     'Red',
     1190,
     '',
     491,
     'Yellow',
     59,
     'Green',
     50,
     'Orange',
     31 ] }

但由于它是动态的,下次我运行测试时它看起来可能会略有不同(可能会添加不同的颜色,或者不再列出当前颜色等)。

我想尝试做的是删除所有数字、多余的逗号等,所以我只剩下一个数组读数(根据上面的示例);

['Black','White','Grey','Blue','Silver','Red','Yellow','Green','Orange']

有没有办法做到这一点,无论是使用 JavaScript 命令还是正则表达式?

【问题讨论】:

标签: javascript arrays filtering


【解决方案1】:

在某些情况下,无法将过滤结果重新分配给原始源参考。就像...

const arr = [1, 2, 3]; arr = arr.filter(/* ... */);

...这将失败。还可能需要处理不允许写入但仍然可以更改的属性。

然后需要一种基于回调的mutating remove 方法,正是filter 要求的那种,其中这个回调函数是是否删除数组项的条件。

function removeEveryMatchingItemByCondition(arr, condition, target) {
  target = (target ?? null);

  let idx = arr.length;
  const copy = Array.from(arr);

  // Processing the array from RIGHT to LEFT keeps the `idx` always in sync
  // with both related array items, the one of the mutated and also the one
  // of the unmutated version of the processed array reference.
  // Thus the `condition` always gets passed the unmutated shallow copy.

  while (idx) {
    if (arr.hasOwnProperty(--idx)) { // take a *sparse array* into account.

      // - keep processing the unmutated shallow copy by the `condition` method.
      // - arguments list ...[elm, idx, arr]... invoked within `target` context.
      if (condition.call(target, copy[idx], idx, copy)) {

        arr.splice(idx, 1); // mutate processed array.
      }
    }
  }
  return arr; // return the mutated array reference.
}


const sampleObject = {
  GenericColour: [
    'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver',
    1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31
  ],
};

removeEveryMatchingItemByCondition(
  sampleObject.GenericColour,
  // exactly what the OP was asking for in first place.
  (item => typeof item === 'number' || String(item).trim() === '')
);
console.log(sampleObject);

removeEveryMatchingItemByCondition(
  sampleObject.GenericColour,
  (item => typeof item === 'string')
);
console.log(sampleObject);
.as-console-wrapper { min-height: 100%!important; top: 0; }

【讨论】:

    【解决方案2】:

    一种方法是在检查length 属性的基础上filter

    对于数字和'',长度值为0(假)。

    const data = [ '', 'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver', 1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31 ];
    
    const res = data.filter(str => str.length);
    
    console.log(res);

    【讨论】:

      【解决方案3】:

      最简单的方法是将 isNaN 传递给 filter 方法。

      const a = [ 'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver', 1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31 ];
      const b = a.filter(isNaN);
      console.log(b);

      【讨论】:

        【解决方案4】:

        您可以使用过滤器功能:

        obj = obj.GenericColour.filter(value => typeof value === 'string' )
        

        【讨论】:

          【解决方案5】:

          您可以使用 array.prototype.filter 来检查数组中的字符串项目,删除所有其他项目,例如数字。查看下面的链接了解更多信息。

          https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

          可能是这样的:

          array.filter((item) => typeof item === "string"); - 这将返回一个新数组,其中仅包含当前数组中的字符串:

          ['Black','White','Grey','Blue','Silver','Red','Yellow','Green','Orange']
          

          【讨论】:

            【解决方案6】:
                int numberArry = []
                arry.forEach(value => if(isNaN(value)) numberArry.push(value));
            

            【讨论】:

              【解决方案7】:

              您可以使用Array#filter,使用typeof 运算符来检查元素是否为字符串。

              const arr = [ 'Black', 5059, 'White', 3610, 'Grey', 3281, 'Blue', 2131, 'Silver', 1408, 'Red', 1190, '', 491, 'Yellow', 59, 'Green', 50, 'Orange', 31 ];
              const res = arr.filter(x => typeof x === 'string' && x);
              console.log(res);

              【讨论】:

                猜你喜欢
                • 2019-09-05
                • 1970-01-01
                • 2019-09-11
                • 2017-03-16
                • 1970-01-01
                • 2014-01-07
                相关资源
                最近更新 更多