Javascript 从数组中删除未定义的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28607451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:05:35  来源:igfitidea点击:

Removing undefined values from Array

javascriptarraysfilter

提问by jAndy

In certain situations, it may happen that we have undefinedor generally falsyvalues in Array structures. For instance when reading and filling data from some unknown sources like Databases or HTML structures. Like

在某些情况下,可能会发生数组结构中存在undefined或通常为值的情况。例如,从一些未知来​​源(如数据库或 HTML 结构)读取和填充数据时。喜欢

var data = [42, 21, undefined, 50, 40, undefined, 9]

Since that might cause trouble when looping over such arrays and working on the elements, what is the best practice to remove undefined(falsy values) ?

由于在遍历此类数组并处理元素时可能会导致麻烦,因此删除undefined(falsy values)的最佳做法是什么?

回答by jAndy

To use Array.prototype.filterhere might be obvious. So to remove only undefined values we could call

Array.prototype.filter这里使用可能很明显。所以为了只删除未定义的值,我们可以调用

var data = [42, 21, undefined, 50, 40, undefined, 9];

data = data.filter(function( element ) {
   return element !== undefined;
});

If we want to filter out all the falsy values (such as 0 or null) we can use return !!element;instead.

如果我们想过滤掉所有的假值(例如 0 或 null),我们可以return !!element;改用。

But we can do it slighty more elegant, by just passing the Booleanconstructor function, respectively the Numberconstructor function to .filter:

但是我们可以做得更优雅一些,只需将Boolean构造函数,分别将Number构造函数传递给.filter

data = data.filter( Number );

That would do the job in this instance, to generally remove any falsyvalue, we would call

在这种情况下,这将完成工作,通常删除任何虚假值,我们会调用

data = data.filter( Boolean );


Since the Boolean()constructor returns trueon truthyvalues and falseon any falsyvalue, this is a very neat option.

由于Boolean()构造函数返回truetruthy值和false任何falsy价值,这是一个非常整洁的选择。

回答by raphaklaus

Inline using lambda

使用 lambda 内联

result.filter(item => item);

回答by Akash Dathan

You can use lodash compactmethod, which removes null, undefinedand ''

您可以使用 lodashcompact方法,该方法删除null,undefined''

_.compact(data)

回答by Diogo Capela

If you have an array of objects and want to remove all nulland undefineditems:

如果您有一组对象并想删除所有nullundefined项目:

[].filter(item => !!item);

回答by Bogdan Potishuk

Array.prototype.reduce()can be used to delete elements by condition from an array but with additional transformation of the elements if required in one iteration.

Array.prototype.reduce()可用于按条件从数组中删除元素,但如果需要在一次迭代中对元素进行额外的转换。



Remove undefinedvalues from array, with sub-arrays support.

undefined从数组中删除值,支持子数组。

function transform(arr) {
    return arr.reduce((memo, item) => {
        if (typeof item !== "undefined") {
            if (Array.isArray(item)) item = transform(item);
            // We can transform item here.
            memo.push(item);
        }
        return memo;
    }, []);
}

let test1 = [1, 2, "b", 0, {}, "", , " ", NaN, 3, undefined, null, 5, false, true, [1, true, 2, , undefined, 3, false, ''], 10];

console.log(transform(test1));


Try it on jsfiddle.net/bjoy4bcc/

jsfiddle.net/bjoy4bcc/试试

回答by vishal

var arr1 = [NaN, 0, 15, false, -22, '',undefined, 47, null];

var array1 = arr1.filter(function(e){ return e;});

document.write(array1);

single lined answer

单行答案

回答by Jorge Londo?o

var a =  ["3","", "6"];
var b =  [23,54,56];
var result = [];

for (var i=0;i<a.length;++i) {
    if (a[i] != "") {
        result[i] = b[i];
    }
}

result = result.filter(function( element ) {
   return element !== undefined;
});

console.log(result);

回答by Tobias Waaentz

As Diogo Capela said, but where 0 is not filtered out as well.

正如 Diogo Capela 所说,但 0 也没有被过滤掉。

[].filter(item => item !== undefined && item !== null)

回答by ROOT

in ES6 this can be achieved by simply using using filter with function return the value like this:

在 ES6 中,这可以通过简单地使用 filter 和函数返回值来实现,如下所示:

const array = [NaN, 0, 15, false, -22, '',undefined, 47, null];
const filteredArr = array.filter(elm => elm);
console.log(filteredArr);

回答by SANTHOSH.SJ

var data = Object.keys(data)

This will remove undefined values but array index will change

这将删除未定义的值,但数组索引会改变