0

Given an array X, write a program that will remove all negative numbers and replace them with a 0. For example, for array X = [2,-1,4,-3] the output of your program should be [2,0,4,0].

So I searched entire Google, but didn't found any good answers.

This is my code by far:

var x = [2, -1, 4, -3]

for(index in x){
    if (index < 0){
    console.log('Yra minusas')
 }
}
John Coleman
  • 51,337
  • 7
  • 54
  • 119
Emilis
  • 17
  • 5
  • 1
    "So I searched entire Google, but didn't found any good answers" -- perhaps because the *point* is to write your own good answer? – John Coleman Mar 09 '19 at 12:29
  • Question is: How to check every number in array so Google comes and shows me every() function :/ – Emilis Mar 09 '19 at 12:39
  • @Emilis you do have the loop body already. That is already more than half the work you needed to do. The only piece needed was to replace the `console.log` with the code to change the value. – VLAZ Mar 09 '19 at 12:41

3 Answers3

1

Array.map() does the trick:

var x = [2, -1, 4, -3];
console.log(x.map(item => item > 0 ? item : 0));

// Or even shorter, as suggested in comments:
console.log(x.map(item => Math.max(item, 0)));
LostMyGlasses
  • 3,074
  • 20
  • 28
  • 1
    For this case, I'd personally `Math.max(item, 0)` than a ternary. The code is working with numbers and a ternary seems overly verbose when the code means "if number is more than X return number otherwise return X". You are really only looking at X or a higher value, hence why `max` makes it less verbose in meaning and in terms of code. As a side-benefit (for me) `Math.max` sounds a bit like Mad Max and it gives me a small chuckle. Hey, I get my laughs where I can. – VLAZ Mar 09 '19 at 12:39
1

The for...in statement iterates over all non-Symbol, enumerable properties of an object but the order of iteration is not guaranteed in any specific order. Thus you should avoid for...in for the iteration of an array.

You can use Array.prototype.map() which will allow you to create a new array with the results of calling a provided function on every element in the calling array.

var x = [2, -1, 4, -3]
x = x.map( i => {
  if(i < 0) i = 0;
  return i;
});

console.log(x)

OR: With Array.prototype.forEach()

var x = [2, -1, 4, -3]
x.forEach((item, i) => {
  if(item < 0)
    x[i] = 0;
});

console.log(x)

OR: With simple for loop

var x = [2, -1, 4, -3]
for(var i=0; i<x.length; i++){
  if(x[i] < 0) 
    x[i] = 0;
}
console.log(x);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Avoid using for..in to loop an array. Alternatively you can use any other array methods.

For example here forEach is used or you can use normal for loop. In this snippet it is checking if each element is greater than 0 , else replacing that element with 0

var x = [2, -1, 4, -3]

x.forEach(function(item, index) {
  if (item < 0) {
    x[index] = 0
  }
})

console.log(x)
VLAZ
  • 26,331
  • 9
  • 49
  • 67
brk
  • 48,835
  • 10
  • 56
  • 78