Tommy A.
Tommy A.

Reputation: 101

Apply conditional statement to every element in array

I have the following code:

if (res[0].toString() == "hello") { res[0] = "string"; };

It works, but I would like to have it not just apply to the first element, but for every element.

Does anyone know how to do this?

Edit: Solved. Thanks people.

Upvotes: 1

Views: 253

Answers (3)

AKX
AKX

Reputation: 169268

That's a .map operation.

const arr = [
  'hello',
  'World',
  'Hello',
  8,
];
arr2 = arr.map((el) => {
  if(el.toString() === 'hello') return 'string';
  return el;  // return the original unchanged
});
console.log(arr2);

will output

[ 'string', 'World', 'Hello', 8 ]

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138437

 res = res.map(it => it === "hello" ? "string" : it);

or

for(const [index, value] of res.entries())
 if(value === "hello") res[index] = "string";

You probably won't need .toString() (I assume it's a string already) and always use === except you really know why == would be better (in very rare cases)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386680

You could reassign a mapped value.

res = res.map(o => o === "hello" ? "string" : o);

Upvotes: 2

Related Questions