sloansparger
sloansparger

Reputation: 67

Deleting certain elements from an array in Javascript

I am trying to code a program that will remove any zeros, empty strings, null, or undefined values in an array. However when I run this array: [1,null,2,3,0,-1,1.1], through the code below it returns the array with the null and 0 value still in the array. Any help?

function cleanArray(arr) {
    var i = 0;
    for (i; i < arr.length; i++) {
        if (arr[i] === 0 || arr[i] === '' || arr[i] === null || arr[i] === undefined) {
            arr.splice(i, 1);
            i--;
        }
        return arr;
    }
}

Upvotes: 2

Views: 574

Answers (6)

rokyed
rokyed

Reputation: 520

  function cleanArray(arr) {
    var i = 0, newArr = [];

    for (i; i < arr.length; i++) {
        if (arr[i]) {
            newArr.push(arr[i]);          
        }

    }
    return newArr;
}

This will work for sure. Hope I was helpful. Here the fiddle: https://jsfiddle.net/rok_ed/coakcd3L/

Upvotes: 0

Ajey
Ajey

Reputation: 8212

You can make use of array filter

var arr = [1,null,2,3,0,-1,1.1];

var filteredArr = arr.filter(function(i){
    // if in javascript checks for truthy values
    if(i) {
     return i;   
    }
});


console.log(filteredArr); // [1, 2, 3, -1, 1.1]

Demo here

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

Use .filter() and the falsy value to remove the unwanted items

function cleanArray(arr) {
    return arr.filter(function (item) {
        return !!item;
        //or return arr[i] !== 0 && arr[i] !== '' && arr[i] !== null && arr[i] !== undefined
    })
}

Upvotes: 2

Jaromanda X
Jaromanda X

Reputation: 1

very simplistically,

arr = arr.filter(function(item) {
    return !!item;
});

but that would let true and other non numeric values through

arr = arr.filter(function(item) {
    return !!item && !isNaN(item);
});

may work better (haven't tested it myself - leaves you with something to try)

Upvotes: 1

Wheeldog
Wheeldog

Reputation: 178

Because of return arr;, which you have placed inside your for loop. As soon as the code runs through the first element, it hits the return and leaves the function with the array as it was after the first run of the loop.

Just move the return statement outside the for loop, like so:

function cleanArray(arr) {
    var i = 0;
    for (i; i < arr.length; i++) {
        if (arr[i] === 0 || arr[i] === '' || arr[i] === null || arr[i] === undefined) {
            arr.splice(i, 1);
            i--;
        }
    }
    return arr;
}

Upvotes: 3

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

You need to move return arr; outside the for loop.

function cleanArray(arr) {
    var i = 0;
    for (i; i < arr.length; i++) {
        if (arr[i] === 0 || arr[i] === '' || arr[i] === null || arr[i] === undefined) {
            arr.splice(i, 1);
            i--;
        }
    }
    return arr;
}

Upvotes: 2

Related Questions