0
var numbers = [1,2,0,3,0,4,0,5];

If I have the above array and I want to remove the 0s and output an array of [1,2,3,4,5] how would I do it?

I have the below code but I am getting an "TypeError: arr.includes is not a function" error...

var zero = 0;

var x = balDiffs.map(function(arr, i) {
  console.log(arr);
  if(arr.includes(zero)) {
    return i;
  }
});
2
  • Array.filter? Commented Jan 4, 2018 at 21:59
  • do you always want to filter zero? Commented Jan 4, 2018 at 22:03

2 Answers 2

3

Use Array#filter with Boolean function as the callback. The Boolean function will return false for 0, and true for other numbers:

var numbers = [1,2,0,3,0,4,0,5];

var result = numbers.filter(Boolean);

console.log(result);

Sign up to request clarification or add additional context in comments.

3 Comments

He did say - "I want to remove the 0s".
As clever as this answer is, it doesn't answer the question based on the heading "remove certain number elements". My read on the question is that zero is just an example in this case. Something like numbers.filter(n => n !== 0), would both be more clear and adaptable to values other than zero.
Both ways work, but I did mean just the 0s. Sorry for the ambiguity. Thank you all of you.
3

Array#map returns an array with the same length as the given array, but it can change the values of each element.

Then you took an element for Array#includes or String#includes but that does not work with numbers.

But even if that works, you would get only zeroes and undefined with the given approach.


You could use Array#filter and filter the unwanted value.

var numbers = [1, 2, 0, 3, 0, 4, 0, 5],
    value = 0,                                   // or any other value
    filtered = numbers.filter(v => v !== value);
    
console.log(filtered);   

Approach with more than one unwanted value.

var numbers = [1, 2, 0, 3, 0, 4, 0, 5],
    unwanted = [0, 3],
    filtered = numbers.filter(v => !unwanted.includes(v));
    
console.log(filtered);   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.