0

I'm given a javascript array that has an amount (not specified) of various elements (strings, numbers, booleans). I need to eliminate strings and booleans. How should I approach it? Should I use typeof?

3
  • Yes, you should use typeof. Commented Jun 24, 2017 at 9:19
  • "Should I use typeof?" That would be the obvious thing to use, yes, probably with Array#filter. Commented Jun 24, 2017 at 9:19
  • n.b. arr.filter creates a new Array, it doesn't modify the existing Array. Make sure you save/return the reference to the result. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jun 24, 2017 at 9:21

4 Answers 4

1

Should I use typeof?

Yes, you should and chain the conditions with logical AND while testing for unequalness.

var array = [NaN, 0, '0', undefined, null, false];

array = array.filter(function (a) {
    return typeof a !== 'string' && typeof a !== 'boolean';
});

console.log(array);

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

Comments

0

You can use typeof operator in filter() method callback, eg:

const myArray = [1,'foo',{name:'bar'},true];
myArray.filter(e => typeof e !== 'string' && typeof e !== 'boolean');

Comments

0

If you use this sort of filtering a lot, you can create a generic type filtering method. The method will receive as params, isType methods for types that will be filtered out.

const array = [NaN, 0, 'string', undefined, null, false];

const isType = (type) => (v) => typeof v === type; // generic type method using partial application
const isString = isType('string'); // detects strings
const isBoolean = isType('boolean'); // detects booleans

const filterTypes = (arr, ...typesToFilter) => 
  arr.filter((v) => !typesToFilter.some((isType) => isType(v))); // remove all items that are of one of the typesToFilter

const result = filterTypes(array, isString, isBoolean);

console.log(result);

Comments

0

You can do it that way using typeof and array.filter() function

    var getNone = x => typeof x !== 'string' && typeof x !=='boolean'; 
    var arr = ['henry',true,1,0,5,'charles',false].filter(getNone);
    console.log(arr);

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.