Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 log the contents like this:

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

As I log the contents I want to check if the current value is bigger than for example var limit = 5;.

If the current value is bigger than limit I want to replace/change that value to let's say the letter A and print it out as such. So my logged arr array would look like this 3,4,5,A,A,A.

I was thinking about 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 either.

like image 681
ejx Avatar asked Jun 02 '13 10:06

ejx


1 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] ); 
});
like image 109
sanchez Avatar answered Oct 03 '22 16:10

sanchez