@FahadM to JavaScriptEnglish • 5 days ago

How do you shallow-copy items from one JavaScript array into a new array?

message-square
0
1
How do you shallow-copy items from one JavaScript array into a new array?
@FahadM to JavaScriptEnglish • 5 days ago

To shallow-copy items from an existing JavaScript array into a new array without mutating the source array, use spread syntax ([...source]) or Array.from(source) (or source.slice()). A shallow copy creates a new outer array containing the same element references—primitives like numbers and strings are copied by value, while nested objects or arrays still share references with the original items.


1. Shallow-Copying Arrays with Spread Syntax ([...arr]) and Array.from()

Use [...source] for concise array cloning and Array.from(source) when converting array-likes (NodeList, arguments, Set) or mapping elements into a new array in a single pass without mutating the original:

// Shallow-copy an array or array-like source into a new array with input guards
function shallowCopyArray(source, mapFn = null) {
  if (source === null || source === undefined) {
    return [];
  }

  if (typeof mapFn === "function") {
    return Array.from(source, (item, index) => mapFn(item, index));
  }

  if (Array.isArray(source)) {
    return [...source];
  }

  if (typeof source[Symbol.iterator] === "function" || typeof source.length === "number") {
    return Array.from(source);
  }

  throw new TypeError("Expected an array, iterable, or array-like object.");
}

// Example usage:
const original = ["html", "css", "js"];
const copy = shallowCopyArray(original);
console.log(copy); // ["html", "css", "js"]
console.log(copy === original); // false
  • Non-mutating new reference: copy !== original, so pushing or popping on copy leaves original untouched.
  • Works with iterables and mapping: Array.from(source, mapFn) cleanly copies array-likes or transforms each slot into a new array without intermediate passes.

2. Shallow-Copying a Slice or Combining Multiple Arrays

Use Array.prototype.slice(start, end) to shallow-copy a sub-range of elements, or combine [...first, ...second] to shallow-merge multiple arrays into a fresh array without modifying any input:

// Shallow-copy a range of items or combine arrays without mutating inputs
function shallowCopyRange(source, start = 0, end = undefined) {
  if (!Array.isArray(source)) {
    throw new TypeError("Expected an array source.");
  }

  return source.slice(start, end);
}

function mergeArraysShallow(...arrays) {
  const merged = [];
  for (const arr of arrays) {
    if (Array.isArray(arr)) {
      merged.push(...arr);
    }
  }
  return merged;
}

// Example usage:
const scores = [10, 20, 30, 40];
console.log(shallowCopyRange(scores, 1, 3)); // [20, 30]
console.log(mergeArraysShallow([1, 2], [3, 4])); // [1, 2, 3, 4]
  • Negative indices supported: source.slice(-2) copies the last two elements without mutating source.
  • Clean concatenation: Spreading multiple arrays into a new array avoids mutating any source array in place.

3. Common Traps to Avoid

Shallow-copying arrays in JavaScript frequently runs into a few pitfalls:

  • Assuming a shallow copy isolates nested objects or arrays: [...arr] only copies top-level references—mutating copy[0].name = "x" will also change original[0].name if both entries point to the same object (use structuredClone() when deep isolation is required).
  • Assigning const copy = original instead of copying: Direct assignment copies only the reference to the same array in memory, so mutating copy mutates original.
  • Spreading non-iterables like null, undefined, or plain objects: [...null] or [...{ a: 1 }] throws a TypeError because plain objects are not iterable—guard inputs first.

TL;DR: Use [...arr], Array.from(arr), or arr.slice() to create a new shallow-copied array without mutating the source, remembering that nested objects inside it still share references unless deep-cloned.