Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a custom function and call it on an array i JavaScript [duplicate]

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()

like image 224
William Avatar asked Aug 10 '26 06:08

William


1 Answers

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)
like image 141
brk Avatar answered Aug 12 '26 21:08

brk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!