Array.prototype.concatLoading saved progress…

Array.prototype.concat

Implement your own version of Array.prototype.concat on Array.prototype under the name myConcat. It takes any number of arguments — arrays and/or single values — and returns a new array: the receiver's elements first, then each argument's elements spread in one level only, then each non-array argument appended as a single element. It does not recurse into nested arrays. It does not mutate the receiver or any argument.

Signature

// Lives on Array.prototype. `this` is the receiver array.
// Each argument is either an array (spread one level) or a value (appended).
// Returns a NEW array — never the receiver, never one of the arguments.
Array.prototype.myConcat = function (...args: unknown[]): unknown[];

Examples

// Receiver is empty, no args: a new empty array.
[].myConcat(); // []
// Arrays are spread one level into the result.
[1, 2].myConcat([3, 4], [5, 6]); // [1, 2, 3, 4, 5, 6]
// Non-array values are appended as a single element each.
[1, 2].myConcat(3, 4, 5); // [1, 2, 3, 4, 5]
// Mix: arrays spread, values appended, in argument order.
[1].myConcat([2, 3], 4, [5], 6); // [1, 2, 3, 4, 5, 6]
// Nested arrays are NOT recursively flattened — only the top-level argument
// is unpacked. The inner [6, 7] stays as a single element.
[1].myConcat([[6, 7]]); // [1, [6, 7]]
[1].myConcat([2, [3, 4]], 5); // [1, 2, [3, 4], 5]

Notes

  • One level only. If an argument is an array, copy its elements one-by-one into the result. Don't recurse into elements that are themselves arrays — myConcat is not flatten.
  • Arrays-as-arguments are spread; the receiver is always spread. The receiver's elements always come first. After that, each argument is checked: if it's an array, spread it; otherwise append as one element.
  • Returns a new array. Never the receiver, never one of the input arrays. Tests check identity (!==).
  • No mutation. The receiver and every argument array must be byte-for-byte identical before and after the call.
  • Zero args is a shallow copy. arr.myConcat() returns a new array with the same elements as arr.
  • Plain arrays only. Treat an argument as "an array to spread" when Array.isArray(arg) is true. Don't try to detect array-likes (arguments, NodeList) — concat doesn't either.
Loading editor…