如何从数组中删除空数组值(“”)?

Posted

技术标签:

【中文标题】如何从数组中删除空数组值(“”)?【英文标题】:How to remove empty array values ("") from an array? 【发布时间】:2019-09-05 04:34:57 【问题描述】:

我有一个二维数组,由 jQuery 的 html 表生成,但有些值是空的,所以会显示 ""

如何删除空值?

  <table>    
    <tr>
      <th>1A</th>
      <th>1B</th>
      <th>1C</th>
    </tr>
    <tr>
      <td>2A</td>
      <td>2B</td>
      <td>2C</td>
    </tr>
    <tr>
      <td></td>
      <td>3B</td>
      <td>3C</td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td>4C</td>
    </tr>
  </table>
<script>
    var columns = $('tr').first().children().map(function(i) 
        return [
            $('tr').map(function()
                return $(this).children().eq(i).text()
            ).get()
        ]
    ).get();
<script>

我已经尝试过以下代码:

for( var i = 0; i < columns[0].length; i++) 
   if ( columns[0][i] === "") 
    columns[0].splice(i, 1); 
   

它适用于一些空值,但由于某种原因并非所有这些值都被删除。

输出:https://imgur.com/e7BAdQK

【问题讨论】:

一些演示代码会很好。请使用jsfiddle或其他东西。因为空白可能来自许多不同的东西。 在for循环之后添加columns = columns.filter(a =&gt; a!="") Remove empty elements from an array in javascript的可能重复 Remove empty strings from array while keeping record Without Loop?的可能重复 【参考方案1】:

你可以像这样使用过滤器:

arr = arr.filter(item => item);

例子:

let arr = ['One', 'Two', '', 'Four', '', ''];
arr = arr.filter(item => item);
console.log(arr);

// Result
// ['One', 'Two', 'Four']

因为空字符串的计算结果为布尔值false。 它适用于所有虚假值,例如0falsenullundefined'' 等。

DEMO

如果你想保留一些值,比如数字0(零),你可以使用item !== undefined。这仅过滤未定义的值。请记住修剪您的字符串或使用正则表达式检查以确保没有空格的空字符串。

【讨论】:

也在 Google Apps 脚本中工作过。【参考方案2】:

创建列数组后,

像这样过滤空值

columns = columns.filter((v) => v != '')

【讨论】:

【参考方案3】:

尝试使用Boolean 函数进行过滤:

columns.filter(Boolean)

这将过滤掉所有虚假值

【讨论】:

【参考方案4】:

这是因为当您 columns[0].splice(i, 1); 时,您正在更改您正在迭代的同一个数组,因此您可能想要使用类似的数组过滤器

columns[0] = columns[0].filter((val) => val != "");

而不是 for 循环

【讨论】:

【参考方案5】:

只需使用过滤功能:-

columns = columns.filter(col => col);

它将删除空值。

【讨论】:

【参考方案6】:

如果某些值可能是 0,请通过检查 "" 进行过滤(因为 0 的计算结果也为 false,因此对于 0 的布尔检查将失败):

columns[0].filter(col => col != "");

【讨论】:

【参考方案7】:

您可以轻松地从数组中删除 emptynullundefined 值。

let my_array = ['One', undefined, 'Two', '', null, 'Four', '', '', 'Five'];

my_array = my_array.filter((item) => item);

console.log(my_array);

【讨论】:

【参考方案8】:

在 ES6 中,假设您有以下数组:

arr = [1, 2, 3, '', false, '4'];

并且您想从数组中删除''(这是一个空值)。你可以这样做:

const filter = (...args) => args.filter(el => el !== '');
console.log(filter(...arr));
[1, 2, 3, false, "4"] // Output

或使用 Map(常规 JS)

const myArr = [1, 2, '', '4'];

noEmptyStringInThisArray = [];

myArr.map((elem) => 
    if (elem !== '') 
    noEmptyStringInThisArray.push(elem);
    
)

console.log(noEmptyStringInThisArray);
// [1, 2, "4"]

【讨论】:

以上是关于如何从数组中删除空数组值(“”)?的主要内容,如果未能解决你的问题,请参考以下文章

如何从 iOS 中的 JSON 数组中删除空对象?

如何删除多维字符串数组中的空元素?

Java中如何判断数组元素是不是为空

如何从 PHP 中的数组中删除值?

如何使用jQuery从数组中删除特定值

如何从数组中删除所有元素[重复]