1

I have a few arrays that are laid out like so:

var row1 = [4,6,4,0,9];
var row2 = [5,2,0,8,1];
var row3 = [2,0,3,1,6];

I want to replace any values that have 0 with a null value. so they would look like:

var row1 = [4,6,4,,9];
var row2 = [5,2,,8,1];
var row3 = [2,,3,1,6];

Any ideas? Basically what I'm trying to do is loop through each value of the array, check to see if it equals 0, and if so replace it with a null value.

Thanks in advance.

5
  • 3
    What part are you stuck at? Your description would just work. Commented May 15, 2013 at 22:32
  • You may also be interested in developer.mozilla.org/en/docs/JavaScript/Reference/… Commented May 15, 2013 at 22:33
  • [4,6,4,,9] isn't valid. Did you mean [4,6,4,null,9]? I.E. maintain the .length property? Or did you want the 0s removed, leaving you with [4,6,4,9]? Commented May 15, 2013 at 22:47
  • @CrescentFresh: It's valid. It just puts a hole in the Array. Given your example... 3 in array; // false Commented May 15, 2013 at 22:55
  • 1
    @squint: neat. .forEach skips element 3 too (whereas something like jQuery.each() does not). OP: are holes acceptable then? Answering it means the different between delete a[index] and a[index] = null, two semantically different things. Commented May 16, 2013 at 2:56

3 Answers 3

7

You can use Array.prototype.map:

row1 = row1.map(function(val, i) {
    return val === 0 ? null : val;
});

http://jsfiddle.net/6Mz38/

Sign up to request clarification or add additional context in comments.

Comments

3

You could do this:

var row1 = [4,6,4,0,9];
var row2 = [5,2,0,8,1];
var row3 = [2,0,3,1,6];

var arrRows = [row1, row2, row3];

for (var i = 0; i < arrRows.length; i++) {
    for (var j = 0; j < arrRows[i].length; j++) {
        if (arrRows[i][j] == 0) {
            arrRows[i][j] = null;
        }
    }
}

Demo: http://jsfiddle.net/npYr2/

1 Comment

arrRows[i][j] == 0 will return true also on null, undefined, "", and NaN. if You want only to convert 0 to tull you should use ===
1

Another possibility is the following

var rows = [row1, row2, row3];

rows = rows.map(function(x){ return x.map(function(y){ return y === 0? null: y})});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.