Code node doesnt support custom method?

here’s my code:

Array.prototype.shuffle = function() {
  const shuffled = [...this]; // Create a copy to avoid mutating original
  for (let i = shuffled.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
  }
  return shuffled;
};

and it gives error:
prototype 'shuffle' does not exist on type 'any[]'

Avoid extending prototypes. Instead of using Array.prototype.shuffle, define a regular function:

function shuffle(arr) {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}

// Usage:
const result = shuffle([1, 2, 3, 4]);

If you really need to extend the prototype, you can do it like this (safely):

interface Array<T> {
shuffle(): T[];
}

Array.prototype.shuffle = function() {
const shuffled = [...this];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
};

const myArray = [1, 2, 3];
const shuffled = myArray.shuffle();

But this may still cause warnings depending on the Code Node sandbox in n8n, and is not the recommended option.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.