ejx
ejx

Reputation: 489

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.

Upvotes: 6

Views: 18420

Answers (4)

Alireza
Alireza

Reputation: 104650

You can simply write somethig like this to handle these scenarios...

Imagine 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];

Upvotes: 4

sanchez
sanchez

Reputation: 4530

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

Upvotes: 9

Thomas Junk
Thomas Junk

Reputation: 5676

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

Upvotes: 1

Matt
Matt

Reputation: 75307

It depends how you were doing the "set this specific value equal to limit". If you were doing;

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

You were changing only the local variable v, rather than the element arr[k]. You can either update arr[k] like in @san.chez answer, or use $.map;

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

  return v;
});

... then filtered would be your array [1,2,4,A,A], and arr would be unchanged. Note the swapping of k and v parameters; jQuery is consistent like that /sarcasm


Note also that both of your code samples are missing the closing }.

Upvotes: 2

Related Questions