0

I would like to filter only numbers bigger than 10 in an array, and change the original variable without causing a side effect.

What i'm doing:

let numbers = [15, 5, 2, 1, 59, 29];
numbers = numbers.filter((number) => {
  if (number > 10) return number;
});

Is working, but this is causing a side effect, right? Is it possible to do that without a side effect, and still use the same variabla name?

Thanks.

Hector Barbossa
  • 5,506
  • 13
  • 48
  • 70
  • Please explain what side effect you are talking about. – Hector Barbossa Aug 01 '16 at 01:32
  • You cannot change a variable without side effects, because changing requires mutation. – Bergi Aug 01 '16 at 01:35
  • All you want to do is not to mutate the original *value* (the array), and your code already does that. You can do whatever you want with your variables as long as you keep them local. – Bergi Aug 01 '16 at 01:36
  • I'm assuming you are using es6, and a compiler, such as Babel? – KevBot Aug 01 '16 at 02:00
  • Mutation is a side effect. What you're asking is: "How can I mutate my variable without causing a side effect ?" That makes no sense. – Mulan Aug 01 '16 at 22:17

1 Answers1

1

So... what you are doing is replacing the original array numbers with a new array with the filtered info in it. If you want to mutate the initial array, it will take much more code. The reason that it will take much more code is that you are talking about modifying the length of an array while you are looping over it, which is a bad practice.

To do it, you might loop through the array once and find all of the indexes that have a value higher than 10. Then once you have all of the indexes, you can loop over them and splice out those sections of the array.

The following code is how you could do it. Not sure about most efficient, but it is a way.

let numbers = [15, 5, 2, 1, 59, 29];
let badIndices = [];
numbers.forEach( (val, idx) => {
    if(val > 10) badIndices.push(idx);
});
badIndices = badIndices.reverse();
badIndices.forEach( i => numbers.splice(i, 1));

You will want to reverse the order of the indices before splicing, otherwise the offset for the subsequent indices will be off. In other words, you will want to start splicing from the end to the front. Otherwise, removing from the front changes the subsequent indices, making the function invalid.

frosty
  • 21,036
  • 7
  • 52
  • 74