0

I got the following array:

var myarr = [['a','b',1],['c','d',2],['e','f',3]]

and I iterate through it in the following way:

$(myarr).each(function(k, v){
     if(this[2] == 2){
         //need to make 'c' and 'd' nulls 
       }
  });

So i need to get the key of the array element and change its 1 and 2 values in order the array look like:

[['a','b',1],['0','0',2],['e','f',3]]

I tried the following:

this[0] = this[1] = null;

but obciously it produced no results. Any ideas how to fix it would be welcome. I can use jQuery. Thank you

3 Answers 3

1

this variable is not binded to the value of the array you are iterating, need to use the value provided by the second argument:

var myarr = [['a','b',1],['c','d',2],['e','f',3]]

$(myarr).each(function(k, v){
   if(v[2] == 2){
       v[0] = v[1] = null; 
     }
});

console.log(myarr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

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

Comments

0

First parameter in callback is index and second is current element so your code should look like this.

var myarr = [['a','b',1],['c','d',2],['e','f',3]]

$.each(myarr, function(i, e) {
  if(e[2] == 2) e[0] = null, e[1] = null
})

console.log(myarr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

0

You can do it directly in javascript with map or forEach:

var myarr = [['a','b',1],['c','d',2],['e','f',3]]

myarr = myarr.map(function(ele, idx){
    if(ele[2] == 2){
        ele[0] = ele[1] = '0';
    }
    return ele;
});

console.log(myarr);

var myarr1 = [['a','b',1],['c','d',2],['e','f',3]]

myarr1.forEach(function(ele, idx){
    if(ele[2] == 2){
        myarr1[idx][0] = myarr1[idx][1] = '0';
    }
});

console.log(myarr1);

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.