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

asked Aug 10, 2017 at 16:47

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>

answered Aug 10, 2017 at 16:50
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>

answered Aug 10, 2017 at 16:51

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);

answered Aug 10, 2017 at 16:54

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.