3

How can I create a functions within JavaScript, that i can then use and chain with others to get results from an array.

I have tried creating a class with multiple methods that can be chain together but that wont allow me to call the functions directly on the array itself.

Example:

[23,45,87,89,21,234,1,2,6,7].CustomFuncEvenNumbers().CustomFuncOrderNumbers()

William
  • 373
  • 2
  • 3
  • 11

1 Answers1

1

You can create the custom function using prototype but to chain another function you need to explicitly return from your custom function , else it will return undefined

let arr = [23, 45, 87, 89, 21, 234, 1, 2, 6, 7];

Array.prototype.CustomFuncEvenNumbers = function() {
  return this.filter(function(item) {
    return item % 2 === 0
  })
}

let k = arr.CustomFuncEvenNumbers().map(item => item * 2);
console.log(k)
brk
  • 48,835
  • 10
  • 56
  • 78
  • would it somehow be possible to not have to create the variable to hold the array instead just use the function on the array? – William Mar 26 '19 at 05:42