Remove empty elements from an array in Javascript

后端 未结 30 2517
无人共我
无人共我 2020-11-21 09:53

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

30条回答
  •  名媛妹妹
    2020-11-21 10:41

    This might help you : https://lodash.com/docs/4.17.4#remove

    var details = [
                {
                    reference: 'ref-1',
                    description: 'desc-1',
                    price: 1
                }, {
                    reference: '',
                    description: '',
                    price: ''
                }, {
                    reference: 'ref-2',
                    description: 'desc-2',
                    price: 200
                }, {
                    reference: 'ref-3',
                    description: 'desc-3',
                    price: 3
                }, {
                    reference: '',
                    description: '',
                    price: ''
                }
            ];
    
            scope.removeEmptyDetails(details);
            expect(details.length).toEqual(3);
    

    scope.removeEmptyDetails = function(details){
                _.remove(details, function(detail){
                    return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
                });
            };
    

提交回复
热议问题