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?
4 Answers
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);
Array#filter.arr.filtercreates 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/…