w3resource

JavaScript: Get an array of function property names from own enumerable properties of an object

JavaScript fundamental (ES6 Syntax): Exercise-48 with Solution

Write a JavaScript program to get an array of function property names from own (and optionally inherited) enumerable properties of an object.

  • Use Object.keys(obj) to iterate over the object's own properties.
  • If inherited is true, use Object.getPrototypeOf(obj) to also get the object's inherited properties.
  • Use Array.prototype.filter() to keep only those properties that are functions.
  • Omit the second argument, inherited, to not include inherited properties by default.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const functions = (obj, inherited = false) =>
  (inherited
    ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]
    : Object.keys(obj)
  ).filter(key => typeof obj[key] === 'function');
function Foo() {
  this.a = () => 1;
  this.b = () => 2;
}
Foo.prototype.c = () => 3;
console.log(functions(new Foo()));
console.log(functions(new Foo(), true));

Sample Output:

["a","b"]
["a","b","c"]

Flowchart:

flowchart: Get an array of function property names from own enumerable properties of an object

Live Demo:

See the Pen javascript-basic-exercise-1-47 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to perform a deep comparison between two values to determine if they are equivalent.
Next: Write a JavaScript program to retrieve a set of properties indicated by the given selectors from an object.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



JavaScript: Tips of the Day

Returns an array of n-tuples of consecutive elements

Example:

const tips_arr = (n, arr) =>  n > arr.length ? [] : arr.slice(n - 1).map((v, i) =>[...arr.slice(i, i + n - 1), v]);
console.log(tips_arr(2, [1, 2, 3, 4, 5])); 
console.log(tips_arr(3, [1, 2, 3, 4, 5]));
console.log(tips_arr(5, [1, 2, 3, 4]));

Output:

[[1, 2], [2, 3], [3, 4], [4, 5]]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
[]