Remove empty elements from an array in Javascript

后端 未结 30 2587
无人共我
无人共我 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:49

    You may find it easier to loop over your array and build a new array out of the items you want to keep from the array than by trying to loop and splice as has been suggested, since modifying the length of the array while it is being looped over can introduce problems.

    You could do something like this:

    function removeFalsyElementsFromArray(someArray) {
        var newArray = [];
        for(var index = 0; index < someArray.length; index++) {
            if(someArray[index]) {
                newArray.push(someArray[index]);
            }
        }
        return newArray;
    }
    

    Actually here is a more generic solution:

    function removeElementsFromArray(someArray, filter) {
        var newArray = [];
        for(var index = 0; index < someArray.length; index++) {
            if(filter(someArray[index]) == false) {
                newArray.push(someArray[index]);
            }
        }
        return newArray;
    }
    
    // then provide one or more filter functions that will 
    // filter out the elements based on some condition:
    function isNullOrUndefined(item) {
        return (item == null || typeof(item) == "undefined");
    }
    
    // then call the function like this:
    var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
    var results = removeElementsFromArray(myArray, isNullOrUndefined);
    
    // results == [1,2,3,3,4,4,5,6]
    

    You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)

提交回复
热议问题