Changing array value when condition is met in javascript

Let's say I have an array var arr = [3,4,5,6,7,9]; , and I register the contents as follows:

 $.each(arr, function(k, v) { console.log(v); } 

When I register the contents, I want to check if the current value is greater than, for example, var limit = 5; .

If the current value is greater than limit , I want to replace / change this value to say the letter A and print it as such. Thus, my registered arr array will look like this: 3,4,5,A,A,A

I was thinking of something like this:

 $.each(arr, function(k,v) { if (v > limit) { // set this specific value equal to limit // log changed value } console.log(v); // otherwise just log the value found }); 

I tried this, but it does nothing, no errors.

+4
source share
4 answers

JSFIDDLE: http://jsfiddle.net/nsgch/8/

 var arr = [3,4,5,6,7,9]; var limit = 5; $.each(arr, function(k,v) { if (v > limit) { arr[k] = 'A'; } console.log( arr[k] ); }); 
+8
source

It depends on how you did "set this value to the limit". If you do

 $.each(arr, function(k,v) { if (v > limit) { v = "A"; // log changed value } console.log(v); // otherwise just log the value found }); 

You only changed the local variable v , not the arr[k] element. You can either update arr[k] , as in @ san.chez's answer , or use $.map ;

 var filtered = $.map(arr, function(v,k) { if (v > limit) { return "A"; } return v; }); 

... then filtered will be your array [1,2,4,A,A] , and arr will not change. Note the replacement of the parameters k and v ; jQuery is consistent with / sarcasm


Also note that both code samples are missing closing } .

+2
source
 var arr = [3,4,5,6,7,9]; arr=arr.map(function(elem){ return elem>5?"A":elem; }); arr.forEach(function(elem){ console.log(elem); }) 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

+1
source

You can just write something like this to handle these scripts ...

Imagine what you have:

 const arr = [0, 1, 6, 12, 0, 78]; 

Use something like:

 arr.map(a => a === 0 ? "a" :a); 

and the result will be:

 ["a", 1, 6, 12, "a", 78]; 
0
source

Source: https://habr.com/ru/post/1484027/


All Articles